javascript变量包含而不是等于

javascript变量包含而不是等于,javascript,variables,Javascript,Variables,在javascript if…else语句中,可以不检查变量是否等于值,而是检查变量是否包含值吗 var blah = unicorns are pretty; if(blah == 'unicorns') {}; //instead of doing this, if(blah includes 'unicorns') {}; //can i do this? 此外,它包含的单词应该是变量的第一个单词。谢谢 if(blah.indexOf('unicorns') == 0) {

在javascript if…else语句中,可以不检查变量是否等于值,而是检查变量是否包含值吗

var blah = unicorns are pretty;
if(blah == 'unicorns') {};       //instead of doing this,
if(blah includes 'unicorns') {}; //can i do this?
此外,它包含的单词应该是变量的第一个单词。谢谢

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.
}
要删除字符串的第一个匹配项,请执行以下操作:

blah = blah.replace('unicorns', '');
要删除字符串的第一个匹配项,请执行以下操作:

blah = blah.replace('unicorns', '');

您还可以使用快速正则表达式测试:

if (/unicorns/.test(blah)) {
  // has "unicorns"
}

您还可以使用快速正则表达式测试:

if (/unicorns/.test(blah)) {
  // has "unicorns"
}

如果第一个单词是指从字符串开头到第一个空格的字符序列,则可以这样做:

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)) {
    // ...  
}
相关问题:


如果第一个单词是指从字符串开头到第一个空格的字符序列,则可以这样做:

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)) {
    // ...  
}
相关问题:


单词是从字符串开始到第一个空格的字符序列吗?那独角兽呢?超级大国是伟大的吗?单词是从字符串开始到第一个空格的字符序列?那独角兽呢超级能力很棒吗?如果/^unicorns/,请检查您需要的第一个单词。testblaht如果/^unicorns/,请检查您需要的第一个单词。testblah@ThomasLai:。@ThomasLai:。