String.prototype.indexOf
Returns the index of the first occurrence of a specified value in a string, or -1 if not found
Syntax
string.indexOf(searchString, position?)Parameters
| Parameter | Type | Description |
|---|---|---|
| searchString | string | Substring to search for |
| position | number | Position to begin searching from |
Return Value
The index of the first occurrence, or -1
Examples
const str = 'Hello World';
console.log(str.indexOf('World')); // 6
console.log(str.indexOf('world')); // -1const email = '[email protected]';
const atIndex = email.indexOf('@');
console.log(email.slice(0, atIndex)); // 'user'let text = 'banana';
let count = 0, pos = 0;
while ((pos = text.indexOf('a', pos)) !== -1) {
count++; pos++;
}
console.log(count); // 3Understanding 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
String.prototype.lastIndexOfReturns the index of the last occurrence of a specified value, searching backwards from the specified position
String.prototype.includesDetermines whether one string may be found within another string, returning true or false
String.prototype.searchExecutes a search for a match between a regular expression and this string, returning the index of the first match
Array.prototype.indexOfReturns the first index at which a given element can be found in the array, or -1 if it is not present
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.