Loading lesson path
Concept visual
Start at both ends
method returns the index (position)
Formula
of the first occurrence of a string in a string, or it returns - 1 if the string is not found:let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");JavaScript counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third, ...
method returns the index of the last occurrence of a specified text in a string:
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");
Both indexOf(), and lastIndexOf()
return -1 if the text is not found:let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("John");Both methods accept a second parameter as the starting position for the search:
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate", 15);methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15, the search starts at position 15, and searches to the beginning of the string.
let text = "Please locate where 'locate' occurs!";
text.lastIndexOf("locate", 15);