如果我有一个数组,并且想知道数组中的任何单词是否在字符串中。我可以使用传统的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);
答案 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);