The JavaScript indexOf() method allows you to find out if a string contains one or more characters, and if so, the starting position of that set of characters
If you’ve ever found yourself saying: “How do I figure out if one string contains a certain character or a sub-string?” then the JavaScript indexOf() method is for you. It returns the starting position of a string, even if it is one character. If that string does not exist, then it returns “-1”. So, if you want to know if a given string even exists at all in another string, simply test to see whether or not the JavaScript method indexOf() returns “-1”. If it does, then the sub-string does not exist. If the return value is “> -1” (i.e. more than -1), then the string does exist.
Example # 1
1 2 3 |
var foo = "Hello world"; var bar = foo.indexOf("football") console.log(bar); |
In Example # 1, we check for the starting position of “football” within the string “Hello world”. Because “football” does not exist in “Hello world”, the return value is “-1”
Example # 2
1 2 3 4 5 6 7 8 |
var foo = "Hello world"; var bar = foo.indexOf("football") if ( bar === -1 ){ console.log('"football" does not exist in the string "hello world"'); } else { console.log('"football does exist in the string "hello world"'); } |
In Example # 2, we use an “if else” condition to test for the string “football” in “hello world”. In this case, it does not exist.
Example # 3
1 2 3 4 5 6 7 8 9 |
var foo = "Hello football world"; var bar = foo.indexOf("football") if ( bar === -1 ){ console.log('"football" does not exist in the string "hello world"'); } else { console.log('"football does exist in the string "hello world", and the starting position of that string is: ' + bar); } |
In Example # 3, we have included the string “football” in “hello world”, so the test returns the starting value of “football”, which is “6”. So, the test evaluates to “true”, the “true” text is displayed, and at the end of that text, we return the starting position of “football”.
Summary
The JavaScript indexOf() method is the best way to find out if one string exists inside of another. If it does, the starting position of that searched string is returned. If the sub-string does not exist, then “-1” is returned; this is a reliable indicator of “does not exist”.
Helpful links for the JavaScript indexOf() method
http://www.w3schools.com/jsref/jsref_indexof.asp
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
http://www.tizag.com/javascriptT/javascript-string-indexOf.php