javascriptで文字列の中に、ある要素のうちどれかがあるかを検出したい場合
端的に言うとツイッターからのデータに対して
['ピカチュウ','カービィ','ハム太郎','シナモン']
のどれかがあるか、あったら
かわいいいいいいいいいいいいいいいい!!!
と自動でリプしたいとします。
どんな方法がわかりやすいかなーと調べていたのですが
JavaScript - ある文字列に対して、配列に入っている文字列のどれかに一致する判定をシンプルに書きたい(28134)|teratail
これがあんまりわかりやすい印象がない(というか若干やりたいことと違う?)ので、友達のコードを参考に書いてみました。
const str = "i can see you again" const wantDetect = ['i', 'you', 'pokemon']; let has = false; for(let d of wantDetect){ if(str.indexOf(d) > -1){ has = true; } } console.log('has', has);
あるいは
const str = "i can see you again" const wantDetect = ['i', 'you', 'pokemon']; let has = false; for(let d of wantDetect){ if(str.indexOf(d) > -1){ has = true; console.log('has', has); break; } }
上のほうが見やすくて好きだけど現実的には下のほうがいいのではないかと。
結果はどちらも
has true
おまけ:何が検出されて、何が検出されなかったかを教えてくれる。
const str = "i can see you again" const wantDetect = ['i', 'you', 'pokemon']; for(let d of wantDetect){ if(str.indexOf(d) > -1){ console.log('detect:', d); }else{ console.log('not detect:', d); } }
結果は
detect: i detect: you not detect: pokemon
これは役に立つのではないか。
ちなみに、友達は
for(const d of wantDetect){
と書いていました。こっちの方がいいのかな。constで書けるならそっちのほうが良さそうだけど、なんとなく直感的ではない。少なくとも私には。
どうでもいいんだけどQiitaの記事とかって結果が書かれていなくて、いまいち初心者にはわかりやすくないなーという印象。