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