Javascript String indexOf()

Introduction

Javascript String indexOf() can locate substrings within another string.

The indexOf() method begins looking for the substring at the beginning of the string.

str.indexOf(searchValue [, fromIndex])
  • searchValue - the string value to search for.
  • fromIndex - Optional, an integer to start the search. Defaults to 0.

If fromIndex value is lower than 0, it uses 0.

If fromIndex value is greater than str.length, it uses str.length.

console.log('hello world'.indexOf('')); // returns 0
console.log('hello world'.indexOf('', 0)); // returns 0
console.log('hello world'.indexOf('', 3)); // returns 3
console.log('hello world'.indexOf('', 8)); // returns 8

With any fromIndex value equal to or greater than the string's length, the returned value is the string's length:

console.log('hello world'.indexOf('', 11)); // returns 11
console.log('hello world'.indexOf('', 13)); // returns 11
console.log('hello world'.indexOf('', 22)); // returns 11

It searches a string for a given substring and return the position.

It returns -1 if the substring isn't found.

let stringValue = "hello world"; 
console.log(stringValue.indexOf("o"));      // 4 

This method accepts an optional second argument that indicates the position to start searching from.

The indexOf() method will start searching from that position and go toward the end of the string, ignoring everything before the start position.

let stringValue = "hello world"; 
console.log(stringValue.indexOf("o", 6));      // 7 



PreviousNext

Related