JavaScript String indexOf() Method

Definition and usage

indexOf() The method returns the first occurrence position of the value in the string.

If the value is not found, then indexOf() The method returns -1.

indexOf() The method is case-sensitive.

See also:

lastIndexOf() method

search() method

match() method

Instance

Example 1

Search for "welcome" in the string:

let text = "Hello world, welcome to the universe.";
let result = text.indexOf("welcome");

Try it yourself

Example 2

Search for "welcome" in the string:

let text = "Hello world, welcome to the universe.";
let result = text.indexOf("Welcome");

Try it yourself

Example 3

Find the first match of "e":

let text = "Hello world, welcome to the universe.";
text.indexOf("e");

Try it yourself

Example 4

Find the first match of "e" starting from position 5:

let text = "Hello world, welcome to the universe.";
text.indexOf("e", 5);

Try it yourself

Example 5

Find the first match of "a":

let text = "Hello world, welcome to the universe.";
text.indexOf("a");

Try it yourself

Syntax

string.indexOf(substring, start)

Parameter

Parameter Description
substring Required. The string to be searched.
start Optional. The starting position (default is 0).

Return value

Type Description
Number

The first position where the search value appears.

If the substring is not found, it returns -1.

Technical details

Return value

returns string If start exists substringThe position after the first substring If the substring is not found, it returns -1.

Description

String.indexOf() The method searches the string from start to end string, to see if it contains the substring substring. The starting position of the search is in the string string at start or string at the beginning (not specified start parameter). If a substringthen String.indexOf() will return substring The first character in string is from 0.string The character position in string there is no match substringthen String.indexOf() The method will return -1.

The difference between String indexOf() and String search()

indexOf() The method cannot search for regular expressions.

search() Cannot use the starting position parameter.

Browser support

indexOf() It is an ECMAScript1 (ES1) feature.

All browsers fully support ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Supports Supports Supports Supports Supports Supports

Related pages

JavaScript String

JavaScript String Methods

JavaScript String Search