javascript variable contains instead of equals - Stack Overflow

in a javascript if...else statement, instead of checking if a variable equals (==) a value, is it possi

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742358958a4429000.html

相关推荐

  • javascript variable contains instead of equals - Stack Overflow

    in a javascript if...else statement, instead of checking if a variable equals (==) a value, is it possi

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信