Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

String.prototype.indexOf

Finds the position of the first occurrence of a substring.

Available since: ES1

Syntax

str.indexOf(searchString, position)

Parameters

ParameterTypeDescription
searchStringstringThe substring to find.
positionnumberOptional. The position to start searching from.

Return value

numberThe position of the match, counting from zero, or `-1` if the substring is not found.

Examples

Position of a match:

console.log('Hello, world'.indexOf('world'));

Output:

7

When there is no match, -1 is returned:

console.log('Hello, world'.indexOf('JS'));

Output:

-1

Notes

If you only need to know whether the substring is present, the string's includes() is simpler.

See also

Related recipes

In the tutorial

  • String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.

Thanks for reading!

Donate to the site — we work hard for you.