JavaScript String indexOf()

The string indexOf() method returns the index of the first occurence of the substring in a string.

Example


indexOf() Syntax

The syntax of the indexOf() method is:

str.indexOf(searchValue, fromIndex)

Here, str is a string.


indexOf() Parameters

The indexOf() method takes in:

  • searchValue - The value to search for in the string. If no string is provided explicitly, "undefined" will be searched.
  • fromIndex (optional) - The index to start the search at. By default it is 0. If fromIndex < 0, the search starts at index 0.

indexOf() Return Value

  • Returns the first index of the value in the string if it is present at least once.
  • Returns -1 if the value is not found in the string.

Note: The indexOf() method is case sensitive.

For empty string searchValue and fromIndex less than the string's length, indexOf returns the value the same as fromIndex.

Similarly, for empty string searchValue and fromIndex greater than the string's length, indexOf returns the string's length.

"nodmek JavaScript".indexOf("", 0); // returns 0
"nodmek JavaScript".indexOf("", 3); // returns 3

// string length here is 20
"nodmek JavaScript".indexOf("", 25); // returns 20
"nodmek JavaScript".indexOf("", 21); // returns 20

Example 1: Using indexOf() method

Output

57
8
45
-1

Example 2: Finding All the Occurrences of an Element

Output

[ 0, 28 ]
[ 52 ]
[]

Recommended Readings: