如果字符串与数组中的多个单词匹配,则Javascript会选择该字符串

Javascript select the string if it matches multiple words in array

本文关键字:字符串 Javascript 选择 数组 如果 单词匹      更新时间:2023-09-26

我有一个字符串"this string中有多个单词",还有一个包含多个单词的数组["There","string","multiple"]。我想将我的字符串与这个数组匹配,如果数组中的所有单词都存在于字符串中,它应该返回true。如果数组中的任何一个单词不在字符串中,则应返回false。

 var str = "There are multiple words in this string";
 var arr = ["There", "string", "multiple"]

这应该返回true。

 var str = "There are multiple words in this string";
 var arr = ["There", "hello", "multiple"]

这应该返回false,因为字符串中不存在"hello"。

如何在纯JavaScript中高效地实现这一点?

使用Array.prototype.every()方法,如果所有元素都通过条件:,则返回true

var str = "There are multiple words in this string";
var arr = ["There", "string", "multiple"]
var arr2 = ["There", "hello", "multiple"]
var result = arr.every(function(word) {
    // indexOf(word) returns -1 if word is not found in string
    // or the value of the index where the word appears in string
    return  str.indexOf(word) > -1
})
console.log(result) // true
result = arr2.every(function(word) {
    return  str.indexOf(word) > -1
})
console.log(result) // false

查看此小提琴

您可以使用Array.prototype.every()

var str = "There are multiple words in this string";
var arr = ["There", "string", "multiple"]
var res = arr.every(function(itm){
 return str.indexOf(itm) > -1;
});
console.log(res); //true 

但请注意,indexOf()将进行通配符搜索,这意味着

"Therearemultiplewordsinthisstring".indexOf("There")

也将返回除CCD_ 4之外的索引。而且它是区分大小写的。