2013-03-01 72 views
1

在JavaScript if ... else语句中,而不是检查变量是否等于(==)值,是否可以检查变量是否包含值?javascript变量包含而不是等于

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

此外,它包含的词应该是变量的第一个词。谢谢!!!

+0

和一个“字”是字符序列形成字符串的开头到第一空间?那么''独角兽是伟大的''呢? – 2013-03-01 00:23:36

回答

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. 
} 

​​

要删除一个字符串的第一次出现:

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

谢谢!另外,我可以从变量中删除“独角兽”吗? – 2013-03-01 00:25:44

+1

@ThomasLai:http://stackoverflow.com/questions/5095000/jquery-remove-string-from-string。 – 2013-03-01 00:34:32

1

你也可以使用一个快速的正则表达式测试:

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

要检查* first *单词,您需要'if(/^unicorns/.test(blah))' – 2013-03-01 00:31:50

1

如果 “第一个字” ,你的意思是从字符串开头到第一个空格的字符序列,那么这就行了它:

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)) { 
    // ... 
} 

More about regular expressions.


相关问题: