JavaScript – Find Index of Substring in String
To find the index of string searchStr
in the string str
in JavaScript, call indexOf() method on this string str
, and pass the other string searchStr
as argument.
indexOf() method returns an integer representing the index of the first occurrence of string searchStr
in the string str
. If string searchStr
is not present in the string str
, then indexOf() returns -1.
Syntax
The syntax to find the index of string searchStr
in the string str
is
str.indexOf(searchStr)
We can also pass an index fromIndex
as second argument. The search for the searchStr
in str
happens from this fromIndex
.
The syntax to find the index of string searchStr
in the string str
from the position fromIndex
is
str.indexOf(searchStr, fromIndex)
Examples
The following is a quick example to find the index of string searchStr
in the string str
in JavaScript.
var str = 'Hello World. Beautiful World.';
var searchStr = 'World';
var result = str.indexOf(searchStr);
In the following example, we take two strings: str
and searchStr
in script, and find the index of string searchStr
in the string str
using indexOf() method. We shall display the result in a div.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="output"></div>
<script>
var str = 'Hello World. Beautiful World.';
var searchStr = 'World';
var index = str.indexOf(searchStr);
document.getElementById('output').innerHTML = 'Index of first occurrence : ' + index;
</script>
</body>
</html>
Now, we will pass a value of 10
for the second argument fromIndex
.
The following is a quick example to find the index of string searchStr
in the string str
from the position fromIndex
in JavaScript.
var str = 'Hello World. Beautiful World.';
var searchStr = 'World';
var fromIndex = 10;
var result = str.indexOf(searchStr, fromIndex);
In the following example, we take two strings: str
and searchStr
in script, and find the index of string searchStr
in the string str
from the position 10
, using indexOf() method.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="output"></div>
<script>
var str = 'Hello World. Beautiful World.';
var searchStr = 'World';
var fromIndex = 10;
var index = str.indexOf(searchStr, fromIndex);
document.getElementById('output').innerHTML = 'Index of first occurrence : ' + index;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to find the index of a substring in this string in JavaScript, using indexOf() method, with examples.