在 JavaScript if...else 语句中,是否可以检查变量是否包含值,而不是检查变量是否等于 (==) 值?
var blah = unicorns are pretty;
if(blah == 'unicorns') {}; //instead of doing this,
if(blah includes 'unicorns') {}; //can i do this?
此外,它包含的单词应该是变量的第一个单词。谢谢!!!
最佳答案
如果“第一个单词”是指从字符串开头到第一个空格的字符序列,则可以这样做:
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.
相关问题:
关于javascript变量包含而不是等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15148222/