2

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!!!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Thomas Lai
  • 875
  • 4
  • 11
  • 19
  • And a "word" is the character sequence form the beginning of the string to the first space? What about `"unicornsuperpowers are great"`? – Felix Kling Mar 01 '13 at 00:23

3 Answers3

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:

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
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.
}

indexOf

To remove the first occurrence of a string:

blah = blah.replace('unicorns', '');
Alex
  • 34,899
  • 5
  • 77
  • 90
1

You can also use a quick regex test:

if (/unicorns/.test(blah)) {
  // has "unicorns"
}
elclanrs
  • 92,861
  • 21
  • 134
  • 171