JavaScript indexOf() method


The indexOf() method in JavaScript is used to determine the index of the first occurrence of a specified substring (search value) within a string. If the substring is not found, it returns -1. This method is case-sensitive and can also accept an optional starting position from which to begin the search.

Syntax:

string.indexOf(searchValue, fromIndex)
  • searchValue: The substring you want to search for within the string.
  • fromIndex (optional): An integer that specifies the index at which to start the search. If omitted, the search starts from index 0 (the beginning of the string).

Return Value:

  • It returns the zero-based index of the first occurrence of searchValue within the string. If the substring is not found, it returns -1.

Example 1: Basic Usage

let text = "Hello, world!"; let index = text.indexOf("world"); console.log(index); // 7

In this example, the substring "world" starts at index 7 in the string "Hello, world!".

Example 2: Case Sensitivity

The indexOf() method is case-sensitive. This means that searching for "hello" will not match "Hello".

let message = "Hello, World!"; console.log(message.indexOf("World")); // 7 console.log(message.indexOf("world")); // -1 (not found)

Example 3: Using fromIndex

You can specify a starting position for the search using the fromIndex parameter. The search begins at the specified index and continues to the end of the string.

let sentence = "The quick brown fox jumps over the lazy dog."; console.log(sentence.indexOf("o")); // 12 (first occurrence) console.log(sentence.indexOf("o", 13)); // 17 (second occurrence) console.log(sentence.indexOf("o", 18)); // 26 (no more occurrences after this, returns -1)

Example 4: Not Finding the Substring

If the specified substring is not found within the string, indexOf() will return -1.

let str = "Hello, world!"; console.log(str.indexOf("example")); // -1

Example 5: Finding Empty Strings

When searching for an empty string (""), indexOf() will return 0, because an empty string is found at the beginning of any string.

let example = "Hello"; console.log(example.indexOf("")); // 0

Example 6: Finding the Last Occurrence

If you need to find the last occurrence of a substring, you should use the lastIndexOf() method, which searches from the end of the string backwards.

let text = "Hello, world! Welcome to the world!"; console.log(text.indexOf("world")); // 7 (first occurrence) console.log(text.lastIndexOf("world")); // 27 (last occurrence)

Summary:

  • The indexOf() method finds the index of the first occurrence of a specified substring within a string and returns -1 if not found.
  • It is case-sensitive and can take an optional fromIndex argument to specify where to start searching.
  • Searching for an empty string returns 0, as an empty substring is considered to be at the start of any string.
  • For finding the last occurrence of a substring, use the lastIndexOf() method instead.