JavaScript正则表达式搜索每个单词和后续单词的开头

javascript regex search start of every word and following word

本文关键字:单词 开头 JavaScript 搜索 正则表达式      更新时间:2023-09-26

我正在尝试根据用户输入编写一个正则表达式,该正则表达式搜索字符串中每个单词的开头和后续单词(不包括空格)。这是我正在使用的当前代码。

var ndl = 'needlehay', //user input
re = new RegExp('(?:^|''s)' + ndl, 'gi'), //searches start of  every word
haystack = 'needle haystack needle second instance';
re.test(haystack); //the regex i need should find 'needle haystack'

任何帮助或建议,我很乐意。

谢谢!

我会遍历指针,并手动尝试每种变体

function check(needle, haystack) {
    if (haystack.replace(/'s/g, '').indexOf(needle) === 0) return true;
    return needle.split('').some(function(char, i, arr) {
        var m = (i===0 ? '' : ' ') + needle.slice(0,i) +' '+ needle.slice(i);
        return haystack.indexOf(m) != -1;
    });
}