最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript variable contains instead of equals - Stack Overflow

programmeradmin0浏览0评论

in a javascript if...else statement, instead of checking if a variable equals (==) a value, is it possible to check if a variable includes a value?

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

also, the word it includes should be the FIRST word of the variable. Thanks!!!

in a javascript if...else statement, instead of checking if a variable equals (==) a value, is it possible to check if a variable includes a value?

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

also, the word it includes should be the FIRST word of the variable. Thanks!!!

Share Improve this question edited Mar 1, 2013 at 0:25 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked Mar 1, 2013 at 0:19 Thomas LaiThomas Lai 8955 gold badges11 silver badges19 bronze badges 1
  • And a "word" is the character sequence form the beginning of the string to the first space? What about "unicornsuperpowers are great"? – Felix Kling Commented Mar 1, 2013 at 0:23
Add a ment  | 

3 Answers 3

Reset to default 2

If by "first word", you mean a character sequence from the beginning of the string to the first space, then this will do it:

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

If instead of a space it can be any white-space character, you should use a regular expression:

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

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

You can also use the special word-boundary character, depending on the language you want to match:

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

More about regular expressions.


Related question:

  • How to check if a string "StartsWith" another string?
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

To remove the first occurrence of a string:

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

You can also use a quick regex test:

if (/unicorns/.test(blah)) {
  // has "unicorns"
}
发布评论

评论列表(0)

  1. 暂无评论