Sunday 30 September 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...