Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

String.prototype.indexOf — finding a substring

String.prototype.indexOf returns the index of the first substring match at or after the starting point obtained by converting and clamping position, or -1 if there is no match. It is case-sensitive and measures indices in UTF-16 code units.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

string.indexOf(searchString)
string.indexOf(searchString, position)

String.prototype.indexOf searches for a literal substring without changing the text. The search starts at the position obtained by converting and clamping position. The method returns the index of the first match, or -1 if there is no match. Indices start at 0 and represent UTF-16 code units, not necessarily complete visible characters. Matching is case-sensitive.

The optional position argument defaults to 0. It is converted to an integer by truncating any fractional part toward zero, then clamped between 0 and the text length. NaN means 0. If position is converted successfully, an empty searchString returns this adjusted position, even if it is at the end of the text. Passing 0n as position throws a TypeError before matching begins.

searchString is converted to a string; omitting it means searching for "undefined". The method does not interpret regular expressions: a supplied RegExp object is also converted to a string.

Test substring presence with result !== -1, not if (result): index 0 is falsy, whereas -1 is truthy. In the example, position changes where searching begins, but the returned index still refers to the entire text.

Examples

const text = "banana";
console.log(text.indexOf("ana"));
console.log(text.indexOf("ana", 2));
console.log(text.indexOf("B"));
console.log(text.indexOf("", 99));
console.log(text.indexOf("ban") !== -1);

Result

1
3
-1
6
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources