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

javascript正则表达式搜索每个单词的开头和后面的单词,javascript,regex,Javascript,Regex,我试图编写一个基于用户输入的正则表达式,搜索字符串中每个单词的开头和后面的单词(不包括空格)。这是我正在使用的当前代码 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 re

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

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

haystack.replace(/\s/g',).indexOf(ndl)!=-1
@adeneo-这难道不符合
postneedle haystack
?@freefaller-这将是我的直觉(这就是为什么这是一个评论而不是答案)是,你不能用一个regexThnx来完成这个脚本,这似乎更彻底。我以前没有使用过某种方法,我需要ie8的polyfill吗?是的,
数组。一些
必须进行多填充,或者重写函数才能在IE8中工作,但这应该不是很难。我对非拉丁字符没有太多经验,这个脚本可以工作吗?只要它是由空格分隔的实际单词,我不明白为什么不能,它使用的只是字符串的长度和空格。