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

javascript regex search start of every word and following word

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

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;
    });
}