如何使用ES6在数组中存在的字符串中查找单词?

时间:2019-06-02 19:35:25

标签: javascript ecmascript-6

如果我有一个数组,并且想知道数组中的任何单词是否在字符串中。我可以使用传统的JavaScript做到这一点,但是如何使用ES6构造做到这一点呢?

示例:

 var wordsInTheStringArray = ["red", "green", "blue"].filter(word => "the red cat. the green gopher.");
 wordsInTheStringArray; // ["red", "green"]

经典方法:

var words = ["red", "green", "blue"]
var string = "the red cat. the green gopher.";
var found = [];

for(var i=0;i<words.length;i++) {
     var hasWord = string.indexOf(words[i])!=-1;
     hasWord ? found.push(words[i]) : 0;
}

console.log(found);

2 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,但不确定我会这样做,则可以使用集合来查找单词的交集。

const wordsInTheStringArray = ["red", "green", "blue"];
const words = "the red and green cat";
const wordsSplit = words.split(" ");

const matches = wordsInTheStringArray.filter(word => new Set(wordsSplit).has(word));

这将为您带来以下结果

["red", "green"]

答案 1 :(得分:1)

这将在字符串中查找字符串。

var wordsInTheStringArray = ["red", "green", "blue"].filter(word => "the red cat. the green gopher.".includes(word));
console.log(wordsInTheStringArray);
要在字符串中查找单词:({greener不计入)

var wordsInTheStringArray = ["red", "green", "blue"].filter(word => "the red cat is not greener".split(' ').includes(word));
console.log(wordsInTheStringArray);
检查单词中的标点符号:(red.将计数)

var wordsInTheStringArray = ["red", "green", "blue"].filter(word => "the cat is red.".split(' ').map(w => w.split('').filter(l => ![".","\,"].includes(l)).join('')).includes(word));
console.log(wordsInTheStringArray);