var str = "I learn JavaScript";
alert( str.indexOf("I learn") ); // zero (first character position index)
alert( str.indexOf("learn") ); // 2
Note: indexOf() searches from the left (beginning of string), and stops after the first instance.
var str = "I learn JavaScript";
alert( str.indexOf("carrot") ); // Not found: returns -1
alert( "I learn JavaScript".indexOf("ear") ); // returns 3
Tip - to use indexOf() as boolean condition, check if the returned value is greater than -1: if( "I learn JavaScript".indexOf("learn") > -1 ) // True if found
alert( "The string was found!" );
var str = "I learn JavaScript";
alert( str.indexOf("javascript") ); // case mismatch → returns -1
alert( str.toLowerCase().indexOf("javascript") ); // Found, returns 8
// Not passing second argument same as passing zero:
alert( "I learn JavaScript".indexOf("ear",0) ); // 3
alert( "I learn JavaScript".indexOf("ear",2) ); // 3
alert( "I learn JavaScript".indexOf("ear",3) ); // 3
alert( "I learn JavaScript".indexOf("ear",4) ); // Not found, returns -1
Note: optional index must be between zero and String.length-1 (last character's position index).
var str = document.URL;
alert( str.substring( str.indexOf("/",7) , str.lastIndexOf("/")+1 ) );
Tip: to search with regular expressions (text pattern matching), use the search() method.
$str = 'I learn PHP';
echo strpos( $str , 'php' ); // Not found, returns 'FALSE'
echo stripos( $str , 'php' ); // Case-insensitive search, returns 8
Sister method: lastIndexOf() looks for one string in another, but starts from the end (right side).