indexOf (JavaScript)

Gets the index of a substring.

Defined in

String (Standard - JavaScript)

Syntax

indexOf(searchString:string) : int

indexOf(searchString:string, position:int) : int

Parameters Description
searchString Substring to be found.
position Position in this object to start search. Defaults to position 0.
Return value Description
int Position of the substring relative to position 0, or -1 if the substring is not found.

Usage

Without the second parameter or with a specification of 0, this method gets the first occurrence of the substring. The second parameter allows you to start the search further in the string to get subsequent occurrences.

Examples

(1) The following example finds the first occurrence of Moscow in the string.
var cities = new String("Paris   Moscow   Tokyo");
var n = cities.indexOf("Moscow");
if (n >= 0) {
	return cities.substring(n);
} else {
	return "Moscow not found";
}

(2) This example counts the occurrences of Moscow in the string.

var cities = new String("Paris   Moscow   Tokyo   Moscow");
var counter = 0;
var n = cities.indexOf("Moscow");
while (n >= 0) {
	counter++;
	n = cities.indexOf("Moscow", n + 1);
}
return "Number of occurrences of Moscow = " + counter;