i

JavaScript

indexOf() and lastIndexOf():

indexOf()method will return the index of the first occurrence of a given text. In JavaScript, the index starts from 0.

Example:

var string = "Jake, John, Jake, Joe";

var position = string.indexOf("Jake");

The variable position will have the index of the start of the first occurrence of the string “Jake”, i.e., 0.

lastIndexOf()is used to identify the index of the last occurrence of a given text.

Example:

var string = “Jake, John, Jake, Joe”;

var position = string.lastIndexOf("Jake");

The variable position will have the value -1 since the search string “Jane” is not present in the variable string.

indexOf() and lastIndexOf() methods accept a second parameter which indicates the starting position for the search.

Example:

var string = “Jake, John, Jake, Joe”;

var position = string.indexOf(“Jake”, 7);

The variable position will have the index of the start of the first occurrence of the string “Jake”, search starting from index 7, i.e., 12.

lastIndexOf() method searches the string from backward, (i.e.), if the second parameter is 7, then it starts the search from 7th position from the last till the beginning of the string.

Example 

var string = “Jake, John, Jake, Joe”;

var position = string.lastIndexOf(“Jake”, 7);

The variable position will have the index of the start of the first occurrence of the string “Jake”, search starting backward from index 7, i.e., 0.

The indexOf() and lastIndexOf() methods will return -1, if the search string is not found in the given string.

Example:

var string = “Jake, John, Jake, Joe”;

var position = string.lastIndexOf(“Jane”);

The variable position will have the value -1 since the search string “Jane” is not present in the variable string.