Javascript String Search








indexOf() and lastIndexOf() searches the sub strings.

They return the position or -1 if the substring isn't found.

indexOf() method begins searching from the start, whereas lastIndexOf() method begins searching from the end.

Example


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

The code above generates the following result.

Search from

Their second optional argument indicates the position to start searching from.

indexOf() starts searching from that position and go toward the end of the string, whereas lastIndexOf() starts searching from the 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

The code above generates the following result.





Example 2

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


var stringValue = "This is a test from, another test.";
var positions = new Array();
var pos = stringValue.indexOf("e");

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

The code above generates the following result.