2016-03-29 20 views
2

我有一个字符串“这个字符串中有多个单词”,我有一个数组有多个单词[“There”,“string”,“multiple”]。我想匹配我的字符串与这个数组,它应该返回true,如果数组中的所有单词都存在于字符串中。如果数组中的任何一个单词不存在于字符串中,它应该返回false。Javascript选择字符串,如果它匹配数组中的多个单词

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"] 

由于“hello”不存在于字符串中,因此应该返回false。

这是如何在纯JavaScript中高效完成的?

+2

打动你的老师:'arr.every(Set.prototype.has.bind(新集( str.split(''))))' – georg

回答

2

使用Array.prototype.every() method,如果所有元素传递条件,则返回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 

this fiddle

+0

不错的一个。尽管在示例代码中,'arr2'可能是错误的。 JSFiddle很好。 – Pimmol

+0

哎呀,错误的复制/粘贴:S。修正! – cl3m

+0

谢谢。有用。 – ASR

1

你可以用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") 

也将返回比-1其他的指标。并且区分大小写。

相关问题