44

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.

0

2 Answers 2

38

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

if (sentence.indexOf('Hello World') >= 0) { alert('Yes'); } else { alert('No'); } 
Sign up to request clarification or add additional context in comments.

6 Comments

Don't just try it. Do it. ;)
@Stephen, is there an extra semantic that !== false adds here or is it just for readability?
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, ok that was my understanding and I was wondering how !== false would work in that situation (still fairly new to javascript).
@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 :)
|
8

Try this instead:

if (sentence.indexOf("Hello World") != -1) { alert("Yes"); } else { alert("No"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.