40

If a sentence contains "Hello World" (no quotes) then I need to return true and do something. Possible sentences could be like this:

var sentence = "This is my Hello World and I like widgets."
var sentence = "Hello World - the beginning of all"
var sentence = "Welcome to Hello World"

if ( sentence.contains('Hello World') ){
alert('Yes');
} else {
alert('No');
}

I know the .contains does not work, so I'm looking for something does work. Regex is the enemy here.

Phrogz
  • 284,740
  • 104
  • 634
  • 722
wish_i_was_nerdy
  • 495
  • 2
  • 5
  • 8

2 Answers2

37

The method you're looking for is indexOf (Documentation). Try the following

if (sentence.indexOf('Hello World') >= 0) { 
  alert('Yes');
} else { 
  alert('No');
}
JaredPar
  • 703,665
  • 143
  • 1,211
  • 1,438
  • 2
    Don't just try it. Do it. ;) – Stephen Nov 22 '10 at 18:07
  • @Stephen, is there an extra semantic that `!== false` adds here or is it just for readability? – JaredPar Nov 22 '10 at 18:09
  • Eh, sorry. I just deleted that part of the comment, Jared. In fact, if the string doesn't exist, `indexOf` returns `-1` not `false`. – Stephen Nov 22 '10 at 18:09
  • @Stephen, ok that was my understanding and I was wondering how `!== false` would work in that situation (still fairly new to javascript). – JaredPar Nov 22 '10 at 18:21
  • Sorry! I didn't mean to confuse! – Stephen Nov 22 '10 at 18:23
  • 1
    @Stephen, no worries. It actually prompted me to do further reading on strict vs. non-strict equality in javascript and I learned quite a bit. So overall a win :) – JaredPar Nov 22 '10 at 18:24
8

Try this instead:

if (sentence.indexOf("Hello World") != -1)
{
    alert("Yes");
}
else
{
    alert("No");
}
Tim S. Van Haren
  • 8,723
  • 2
  • 29
  • 34