Gets the index of a substring.
| 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. |
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;