bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Working with Data
JavaScript•Working with Data

JavaScript String Search

Concept visual

JavaScript String Search

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

String Search Methods

String indexOf()

String lastIndexOf()

String search()

String match()

String matchAll()

String includes()

String startsWith()

String endsWith()

See Also:

String Tutorial

String Methods

String Templates

String Reference

JavaScript String indexOf()

The indexOf()

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:

Example

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, ...

JavaScript String lastIndexOf()

The lastIndexOf()

method returns the index of the last occurrence of a specified text in a string:

Example

let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");
Both indexOf(), and lastIndexOf()
return -1 if the text is not found:

Example

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:

Example

let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate", 15);

The lastIndexOf()

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.

Example

let text = "Please locate where 'locate' occurs!";
text.lastIndexOf("locate", 15);

Previous

RegExp Character Classes

Next

JavaScript Number Reference