The indexOf() method returns the first occurrence of a specified string value in a string.
Syntax
stringObject.indexOf(searchvalue,fromindex)
Parameter Description
searchvalue Required. Specifies the string value to be retrieved.
fromindex optional integer parameter. Specifies the position in the string to begin searching. Its legal values are 0 to stringObject.length - 1. If this parameter is omitted, the search will start from the first character of the string.
Explanation
This method will retrieve the string stringObject from beginning to end to see if it contains the substring searchvalue. The starting position of the search is at the fromindex of the string or the beginning of the string (when fromindex is not specified). If a searchvalue is found, the position of the first occurrence of searchvalue is returned. Character positions in stringObject start from 0.
Tips and Notes
Note: The indexOf() method is case sensitive!
Note: If the string value to be retrieved does not appear, this method returns -1.
Example
In this example, we will perform different searches within the "Hello world!" string: