Favorites

JavaScript String.prototype.indexOf() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
String.prototype.indexOf()
JavaScript String Instance methodThis method is supported by all modern browsers.
Updated 28th November 2026

The indexOf() method returns the position of the first occurrence of some text in a string, or -1 if it isn't found.

Description

The indexOf() method searches a string and returns the index of the first occurrence of the search text, or -1. The search is case-sensitive. Use includes() if you only need a yes or no, and search() to search with a regular expression.

An empty search string returns the starting position, or the string's length if the position is beyond the end. The position argument makes it easy to find every occurrence in a loop: start the next search one character after the last match. Negative positions are treated as 0.

The returned index is in UTF-16 code units, which matches how slice() and substring() count, so you can use it directly to cut the string, for example taking everything before the first @ in an email address.

Syntax

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

Parameters

  • searchStringThe text to search for.
  • positionOptional. The index to start from. Defaults to 0.

Return Value

The index of the first match, or -1 if it isn't found.

Example

const text = 'To be, or not to be';
console.log(text.indexOf('be'));
console.log(text.indexOf('be', 4));
console.log(text.indexOf('Be'));

Browser Support

The following information will show you the current browser support for the String.prototype.indexOf() method. Hover over a browser icon to see the version that first introduced support for this method.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee