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
string.indexOf(what to search, [where to start search]);
Example
Let's find the position of the first occurrence of a substring:
let str = 'ab cd cd cd ef';
let res = str.indexOf('cd');
console.log(res);
The code execution result:
3
Example
Let's specify the position where to start the search:
let str = 'ab cd cd cd ef';
let res = str.indexOf('cd', 4);
console.log(res);
The code execution result:
6
Example
Now let's look for a non-existent substring:
let str = 'ab cd cd cd ef';
let res = str.indexOf('xx');
console.log(res);
The code execution result:
-1
Example
Let's look for a substring specified in the wrong case for the current string:
let str = 'ab cd cd cd ef';
let res = str.indexOf('CD');
console.log(res);
The code execution result:
-1
See also
-
the
startsWithmethod
that checks the start of a string -
the
endsWithmethod
that checks the end of a string -
the
lastIndexOfmethod
that searches for the last occurrence of a substring -
the
includesmethod
that searches for a string -
the
atmethod
that searches for a string character