Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, or -1 if the value is not found.
String
indexOf(searchValue, fromIndex)
searchValue
A string representing the value for which to search.
fromIndex
(Optional) The location within the calling string to start the search from. It can be any integer between 0 and 1 less than the length of the string. The default value is 0.
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character of a string called stringName is stringName.length - 1.
If stringName contains an empty string (""), indexOf returns an empty string.
The indexOf method is case-sensitive. For example, the following expression returns -1:
"Blue Whale".indexOf("blue")
The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world."
var anyString="Brave new world" //Displays 8 Console.Write("<P>The index of the first w from the beginning is " + anyString.indexOf("w")) //Displays 10 Console.Write("<P>The index of the first w from the end is " + anyString.lastIndexOf("w")) //Displays 6 Console.Write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new")) //Displays 6 Console.Write("<P>The index of 'new' from the end is " + anyString.lastIndexOf("new"))
The following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first write method displays 19. But because the indexOf method is case-sensitive, the string "cheddar" is not found in myCapString, so the second write method displays -1.
myString="brie, pepper jack, cheddar" myCapString="Brie, Pepper Jack, Cheddar" Console.Write('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar")) Console.Write('myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar"))
The following example sets count to the number of occurrences of the letter x in the string str:
String:charAt, String:lastIndexOf, String:split