Skip to main content

indexOf() JavaScript String Method – How to Get Text Index

Whenever you use indexOf() on a string, the method does the following:

  1. It searches its calling string for the method's first argument.
  2. It returns the index position of the first match, or -1 if the method found no match.
note

A calling string is a string on which you used indexOf(). So, in "Hello, world!".indexOf("world"), "Hello, world!" is the calling string.

Syntax of the indexOf() Method

Here is indexOf()'s syntax:

callingString.indexOf(valueToFind, startIndex)

The snippet above shows that indexOf() accepts two arguments: a valueToFind and a startIndex.

Argument 1: valueToFind

A valueToFind is the first argument accepted by the indexOf() method. It defines the value you wish to find in the calling string.

Example 1: Find the index of day

"SunDay, Tuesday, and Friday are good Days".indexOf("day");

// The invocation above will return:

12

Try it on StackBlitz

Example 2: Find the index of Day

"SunDay, Tuesday, and Friday are good Days".indexOf("Day");

// The invocation above will return:

3

Try it on StackBlitz

Example 3: Find the index of 3

"Day1, day-3, and day 6 are good Days".indexOf(3);

// The invocation above will return:

10

Try it on StackBlitz

Argument 2: startIndex

The startIndex argument is optional. It specifies the index position where you want the computer to start searching for the valueToFind argument.

Example 1: Find the index of day from the 13th index position

"SunDay, Tuesday, and Friday are good Days".indexOf("day", 13);

// The invocation above will return:

24

Try it on StackBlitz

The startIndex argument's default value is 0. Therefore, if omitted or negative, the search will begin at index 0.

Here's an example:

"SunDay, Tuesday, and Friday are good Days".indexOf("day", -13);

// The invocation above will return:

12

Try it on StackBlitz

Example 2: Find the index of Day from the 4th index position

"SunDay, Tuesday, and Friday are good Days".indexOf("Day", 4);

// The invocation above will return:

37

Try it on StackBlitz

Suppose startIndex is greater than the calling string's length. In such a case, the computer will ignore the search.

Here's an example:

"SunDay, Tuesday, and Friday are good Days".indexOf("Day", 75);

// The invocation above will return:

-1

Try it on StackBlitz

tip
  • To find the last occurrence of a string, use lastIndexOf().
  • Suppose you need to use regular expression as the valueToFind argument. In that case, use search().
  • To do a global search for all matches, use match().

Overview

indexOf() searches its calling string for the first occurrence of the method's string argument.

If you like this article, please Tweet it.

Thanks for reading!