[英]How to find a word in a string that exists in an array using ES6?
If I have an array and I want to find out if any of the words in the array are in a string. 如果我有一个数组,并且想确定数组中的任何单词是否在字符串中。 I can do that with traditional JavaScript but how would I do that using ES6 constructs?
我可以使用传统的JavaScript做到这一点,但是如何使用ES6构造做到这一点呢?
Example: 例:
var wordsInTheStringArray = ["red", "green", "blue"].filter(word => "the red cat. the green gopher.");
wordsInTheStringArray; // ["red", "green"]
Classic Method: 经典方法:
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);
If I understand you correctly, not sure that I do, you can use sets to find the intersections of the words. 如果我正确理解了您的信息(不确定我是否理解),则可以使用集合来查找单词的交集。
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));
That would give you the following result 那会给你以下结果
["red", "green"]
This will look for strings in the string. 这将在字符串中查找字符串。
var wordsInTheStringArray = ["red", "green", "blue"].filter(word => "the red cat. the green gopher.".includes(word)); console.log(wordsInTheStringArray);
greener
will not count)
greener
不会计数)
var wordsInTheStringArray = ["red", "green", "blue"].filter(word => "the red cat is not greener".split(' ').includes(word)); console.log(wordsInTheStringArray);
red.
will count)
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.