String

String.prototype.indexOf

Returns the index of the first occurrence of a specified value in a string, or -1 if not found

Syntax

JavaScript
string.indexOf(searchString, position?)

Parameters

ParameterTypeDescription
searchStringstringSubstring to search for
positionnumberPosition to begin searching from

Return Value

The index of the first occurrence, or -1

Examples

Basic Usage
const str = 'Hello World';
console.log(str.indexOf('World')); // 6
console.log(str.indexOf('world')); // -1
Practical Example
const email = '[email protected]';
const atIndex = email.indexOf('@');
console.log(email.slice(0, atIndex)); // 'user'
Advanced Usage
let text = 'banana';
let count = 0, pos = 0;
while ((pos = text.indexOf('a', pos)) !== -1) {
  count++; pos++;
}
console.log(count); // 3

Understanding String.prototype.indexOf

The String.prototype.indexOf method in JavaScript returns the index of the first occurrence of a specified value in a string, or -1 if not found. It belongs to the String object and is one of the most widely used methods for working with string values in modern JavaScript and TypeScript applications.

The method signature is string.indexOf(searchString, position?). It accepts 2 parameters: searchString, position. When called, it returns the index of the first occurrence, or -1. Understanding when and how to use indexOf() helps you write more expressive, readable code.

Common use cases for String.prototype.indexOf include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like string-lastindexof, string-includes, string-search, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for String.prototype.indexOf is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More String Methods

Other methods in the String object

Related Tools

More String Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.