String indexOf()
syntax: |
string.indexOf(substring[, offset]) |
where: |
substring - substring to search for within string.
offset - optional integer argument which specifies the position within string at which the search is to start. Default is 0.
|
return: |
number - index of the first appearance of a substring in a string, else -1, if substring not found.
|
description: |
String indexOf() searches the string for the string specified in substring. The search begins at offset if offset is specified; otherwise the search begins at the beginning of the string. If substring is found, String indexOf() returns the position of its first occurrence. Character positions within the string are numbered in increments of one beginning with zero.
|
see: |
String charAt(), String lastIndexOf(), String substring()
|
example: |
var string = "what a string"; string.indexOf("a")
// returns the position, which is 2 in this example, // of the first "a" appearing in the string. // The method indexOf()may take an optional second // parameter which is an integer indicating the index // into a string where the method starts searching // the string. For example:
var magicWord = "abracadabra"; var secondA = magicWord.indexOf("a", 1);
// returns 3, index of the first "a" to be found in // the string when starting from the second letter of // the string. // Since the index of the first character is 0, the // index of second character is 1. |