2

javascriptのif...elseステートメントで、変数が値と等しい(==)かどうかをチェックする代わりに、変数に値が含まれているかどうかをチェックすることは可能ですか?

var blah = unicorns are pretty;
if(blah == 'unicorns') {};       //instead of doing this,
if(blah includes 'unicorns') {}; //can i do this?

また、含まれる単語は、変数の最初の単語である必要があります。ありがとう!!!

4

3 に答える 3

2

「最初の単語」とは、文字列の先頭から最初のスペースまでの文字シーケンスを意味する場合、次のようになります。

if  ((sentence + ' ').indexOf('unicorns ') === 0) {
    //         note the trailing space ^
} 

スペースの代わりに任意の空白文字を使用できる場合は、正規表現を使用する必要があります。

if (/^unicorns(\s|$)/.test(sentence)) {
    // ...
}

// or dynamically
var search = 'unicorns';
if (RegExp('^' + search + '(\\s|$)').test(sentence)) {
    // ...
}

一致させたい言語に応じて、特殊な単語境界文字を使用することもできます。

if (/^unicorns\b/.test(sentence)) {
    // ...  
}

正規表現の詳細。


関連する質問:

于 2013-03-01T00:29:07.220 に答える
1
if(blah.indexOf('unicorns') == 0) {
    // the string "unicorns" was first in the string referenced by blah.
}

if(blah.indexOf('unicorns') > -1) {
    // the string "unicorns" was found in the string referenced by blah.
}

indexOf

最初に出現する文字列を削除するには:

blah = blah.replace('unicorns', '');
于 2013-03-01T00:20:48.243 に答える
1

簡単な正規表現テストを使用することもできます:

if (/unicorns/.test(blah)) {
  // has "unicorns"
}
于 2013-03-01T00:25:42.813 に答える