To find the index of a substring in JavaScript, you can use the indexOf
method of the String object.
In this example,
str
with a string value.indexOf
method of the string object str
to find the index of a specific substring.indexOf
method returns the starting index of the substring in the string.let str = "Hello World";
let index = str.indexOf("World");
console.log(`Index of substring is: ${index}`);
Index of substring is: 6
In this example,
str1
and str2
with different values.indexOf
method of str1
to find the index of str2
within str1
.indexOf
method returns the starting index of str2
in str1
.let str1 = "apple banana cherry banana";
let str2 = "cherry";
let index = str1.indexOf(str2);
console.log(`Index of substring is: ${index}`);
Index of substring is: 13
In this tutorial, we learned How to find the Index of Substring in JavaScript language with well detailed examples.