How to use split() and pop() In Javascript
Using split() and pop(), this approach splits the text at the substring, extracts the last segment, and calculates the index of its start within the original string.
Syntax:
const segments = str.split(substring);
const lastIndex = str.length - segments.pop().length - substring.length;
Example: In this example, the index of the last occurrence of “Science” is found by splitting the string and calculating the index based on the lengths of segments and substring.
function lastIndexOfSubstring(str, substr) {
let lastIndex = -1;
for (let i = 0; i <= str.length - substr.length; i++) {
if (str.substr(i, substr.length) === substr) {
lastIndex = i;
}
}
return lastIndex;
}
console.log(lastIndexOfSubstring("hello world hello", "hello")); // Output: 12
Output
Last occurrence of Science found at index :26
JavaScript Program to Find the Index of the Last Occurrence of a Substring in a String
Finding the index of the last occurrence of a substring in a string is a common task in JavaScript. The last occurrence of a substring in a string in JavaScript refers to finding the final position where a specified substring appears within a given string. We may want to know the position of the last occurrence of a specific substring within a given string.
There are several methods that can be used to find the index of the last occurrence of a substring in a string in JavaScript, which are listed below:
Table of Content
- Using lastIndexOf() Method
- Using Regular Expression
- Using split() and pop()
- Using a Loop
- Using Array.prototype.reduceRight() Method
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us