Search for a string using Javascript

if (str.indexOf("Yes") >= 0)

 

This is a powerful tool. The variable str contains the text you want to search. “Yes” is an example of what you could search for. It will be >=0 if the string is found in the search.

 

Here is a good example for how to see if its a negative number.

var isnegative=number.indexOf("-")>=0? true : false ;

 

If string passed in is likeĀ  number= 10 will return true
If number = -10 then will return false.

 

While enjoying some reading of the Mozilla Developer Network docs, I have stumbled on to a bit of “best practice” techniques:

Note that ‘0’ doesn’t evaluate to true and ‘-1’ doesn’t evaluate to false. Therefore, when checking if a specific string exists within another string the correct way to check would be:

"Blue Whale".indexOf("Blue") != -1; // true
 "Blue Whale".indexOf("Bloe") != -1; // false

So my final snippet for checking if a string is in another string is as follows.

var mystring - "Yes I want to respond."; If (mystring.indexOf("Yes") != -1){console.log("They want to respond");)} 

Leave a Reply