Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS String Search

String Search Methods

JavaScript String Search encompasses methods such as indexOf(), lastIndexOf(), and search(), which facilitate locating substrings within strings and determining their positions.

Additional methods include:

  • String match()
  • String matchAll()
  • String includes()
  • String startsWith()
  • String endsWith()

JavaScript String indexOf()

The indexOf() method retrieves the index (position) of the initial occurrence of a string within another string. If the string is not found, it returns -1.

Example

let text = “Please locate where ‘locate’ occurs!”;
let index = text.indexOf(“locate”);

Note

In JavaScript, positions are counted starting from zero.

Therefore, 0 represents the first position in a string, 1 represents the second position, 2 represents the third position, and so forth.