检查字符串变量是否在文本中

Javascript: Check if string variable is in text

本文关键字:文本 是否 字符串 变量 检查      更新时间:2023-09-26

我有一个文本字符串和一个单词数组。我想看看这些词是否出现在文本中,如果它们确实把它们放在另一个数组中。

I have try:

var aray = ['dies','jam', 'jug', 'march', 'one', 'men', 'all'],
testText = "If one of them dies I will notice that one off my men is missing"
i,found = [];
for(i=0; i < aray.length; i++){
    searchTerm = "/''b" + aray[i] + "/gi";
    found = testText.match(searchTerm)
}

但发现总是"null"

我读到也许我应该构造一个新的RegExp对象,所以我尝试:

for(i=0; i < aray.length; i++){
    searchTerm = "/''b" + aray[i] + "/gi";
    found = testText.match(new RegExp(searchTerm, 'gi'));
}

但仍然发现= "null"。我试过改变正则表达式,但如果我把正则表达式直接放入testText。匹配即可,如:

searchTerm = "/''b" + 'dies' + "/gi";

您可以使用下划线或lodash或自定义数组交集函数:

var array = ['dies','jam', 'jug', 'march', 'one', 'men', 'all'],
testText = "If one of them dies I will notice that one off my men is missing";
var diff = _.intersection(array, testText.split(' '));
console.log(diff);

—> ["dies", "one", "men"]

http://jsfiddle.net/S65Vd/1/