2016-03-29 15 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

があなたの先生インプレス参照してください。 str.split( '')))) ' – georg

答えて

2

使用Array.prototype.every() method、すべての要素が条件を渡す場合はtrueを返す:( `arr.every(Set.prototype.has.bind(新しいセット:

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 

をそれを行うしかし

"Therearemultiplewordsinthisstring".indexOf("There") 

-1以外のインデックスを返します。つまり、indexOf()は、ワイルドカード検索を実行することに注意してくださいすることができます。大文字と小文字が区別されます。

関連する問題