Javascript - String Search Methods

Introduction

To search inside a string use indexOf() and lastIndexOf().

Both methods search a string for a given substring and return the position or -1 if the substring isn't found.

indexOf() method begins looking for the substring at the beginning of the string, whereas the lastIndexOf() method begins looking from the end of the string.

var stringValue = "hello world";
console.log(stringValue.indexOf("o"));         //4
console.log(stringValue.lastIndexOf("o"));     //7

Here, the first occurrence of the string "o" is at position 4, which is the "o" in "hello".

The last occurrence of the string "o" is in the word "world", at position 7.

If there is only one occurrence of "o" in the string, then indexOf() and lastIndexOf() return the same position.

Each method accepts an optional second argument that indicates the position to start searching from within the string.

indexOf() method will start searching from that position and go toward the end of the string, whereas lastIndexOf() starts searching from the given position and continues searching toward the beginning of the string.

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

Using this second argument allows you to locate all instances of a substring by looping callings to indexOf() or lastIndexOf():

var stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
var positions = new Array();
var pos = stringValue.indexOf("e");

while(pos > -1){
    positions.push(pos);
    pos = stringValue.indexOf("e", pos + 1);
}

console.log(positions);    //"3,24,32,35,52"