indexOf method

The indexOf method searches for a substring in a string. In the first parameter, we specify the desired substring in the case we need (capital letters or small). The method will return the position of the first match, and if it is not found, it will return -1. As the second optional parameter, you can pass the number of the character from where the search should start.

Syntax

javascriptstring.indexOf(what to search, [where to start search]);

Example

Let's find the position of the first occurrence of a substring:

javascriptlet str = 'ab cd cd cd ef';
let res = str.indexOf('cd');

console.log(res);

The code execution result:

javascript3

Example

Let's specify the position where to start the search:

javascriptlet str = 'ab cd cd cd ef';
let res = str.indexOf('cd', 4);

console.log(res);

The code execution result:

javascript6

Example

Now let's look for a non-existent substring:

javascriptlet str = 'ab cd cd cd ef';
let res = str.indexOf('xx');

console.log(res);

The code execution result:

javascript-1

Example

Let's look for a substring specified in the wrong case for the current string:

javascriptlet str = 'ab cd cd cd ef';
let res = str.indexOf('CD');

console.log(res);

The code execution result:

javascript-1

See also

  • the startsWith method
    that checks the start of a string
  • the endsWith method
    that checks the end of a string
  • the lastIndexOf method
    that searches for the last occurrence of a substring
  • the includes method
    that searches for a string
  • the at method
    that searches for a string character