The indexOf() method of the String class in JavaScript returns the index within the calling String object of the first occurrence of the specified value, searchString, starting the search at fromIndex. Returns -1 if the value is not found.
There are 2 variations for the syntax of String.indexOf() method. They are:
indexOf(searchString)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchString | required | The string to search for within this string. |
This method returns the index within the calling String object of the first occurrence of searchString.
Returns value of type Number
.
indexOf(searchString, fromIndex)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchString | required | The string to search for within this string. |
fromIndex | optional | The position in the calling string to start the search from. Defaults to 0. |
This method returns the index within the calling String object of the first occurrence of searchString, starting the search at fromIndex.
Returns value of type Number
.
In JavaScript, we can use the indexOf()
method to find the first occurrence of a specified substring.
For example,
str
with the value 'Hello, world!'
.indexOf()
method with the argument 'world'
to find the first occurrence of the substring.index
.index
to the console using the console.log()
method.const str = 'Hello, world!';
const index = str.indexOf('world');
console.log(index);
7
In JavaScript, we can use the indexOf()
method to find the first occurrence of a specified substring, starting from a given position.
For example,
str
with the value 'Hello, world!'
.indexOf()
method with the arguments 'o'
and 5
to find the first occurrence of the character 'o'
starting from position 5
.index
.index
to the console using the console.log()
method.const str = 'Hello, world!';
const index = str.indexOf('o', 5);
console.log(index);
8
In JavaScript, we can use the indexOf()
method to search for a substring that does not exist in the string.
For example,
str
with the value 'Hello, world!'
.indexOf()
method with the argument 'JavaScript'
to search for the substring 'JavaScript'
within the string.index
.index
to the console using the console.log()
method.const str = 'Hello, world!';
const index = str.indexOf('JavaScript');
console.log(index);
-1
In this JavaScript tutorial, we learned about indexOf() method of String: the syntax and few working examples with output and detailed explanation for each example.