Sunday, September 30, 2018

javascript - if sentence contains string




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.


Answer



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



if (sentence.indexOf('Hello World') >= 0) { 
alert('Yes');

} else {
alert('No');
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...