JavaScript Program to Find the Index of the Last Occurrence of a Substring in a String
Last Updated :
10 Jul, 2024
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:
We will explore all the above methods along with their basic implementation with the help of examples.
Using lastIndexOf() Method
The lastIndexOf() method in JavaScript is used to find the index of the last occurrence of a specified substring in a string. It searches the string from the end to the beginning and returns the index of the last occurrence of the substring, or -1 if the substring is not found.
Syntax:
str.lastIndexOf(searchValue , index)
Example: In this example, we find the last occurrence index of the substring "Computer" in the text. It displays the index if found; otherwise, indicates absence.
JavaScript
const text = "GeeksforGeeks, A Computer science Portal.";
// Substring to search for
const substring = "Computer";
// Using lastIndexOf() method
const lastIndex = text.lastIndexOf(substring);
if (lastIndex !== -1) {
console.log(`Last occurrence of '
${substring}
' found at index ${lastIndex}`);
} else {
console.log(
`'${substring}' not found in the text.`);
}
OutputLast occurrence of '
Computer
' found at index 17
Using Regular Expression
Regular expressions provide a powerful way to search for patterns in strings. You can use the RegExp constructor along with the exec() method to find the last occurrence of a substring in a string.
Syntax:
const regex = new RegExp(substring, 'g');
Example: In this example,we are using a RegExp and exec(), to finds the last occurrence index of the substring "sample" in the text and displays it.
JavaScript
const text = "Hello, this is a sample text. This text is a sample.";
// Substring to search for
const substring = "sample";
// Create a regular expression
const regex = new RegExp(substring, 'g');
let match;
let lastIndex = -1;
while ((match = regex.exec(text)) !== null) {
lastIndex = match.index;
}
if (lastIndex !== -1) {
console.log(`Last occurrence of '
${substring}
' found at index
${lastIndex}`);
} else {
console.log(`'${substring}
' not found in the text.`);
};
OutputLast occurrence of '
sample
' found at index
45
Using split() and pop()
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.
JavaScript
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
OutputLast occurrence of Science found at index :26
Using a Loop
Using a loop, iterate through the string, comparing substrings of the same length as the target substring with it. Track the index of the last occurrence. Return the index found after iterating through the entire string.
Example: In this example we defines a function lastIndexOfSubstring that finds the last occurrence of a substring within a string by iterating through the string and updating the last index each time the substring is found.
JavaScript
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"));
Using Array.prototype.reduceRight() Method
The Array.prototype.reduceRight() method applies a function against an accumulator and each value of the array (from right to left) to reduce it to a single value. We can use this method to find the last occurrence of a substring by iterating the string array in reverse.
Example: In this example, we use reduceRight() to find the last occurrence index of the substring "example" in the given text. The method accumulates the index if the substring is found, otherwise returns -1.
JavaScript
const text = "This is an example text with example as a repeated example.";
// Substring to search for
const substring = "example";
// Using reduceRight() method
const lastIndex = text.split('').reduceRight((acc, _, i, arr) => {
if (arr.slice(i, i + substring.length).join('') === substring && acc === -1) {
return i;
}
return acc;
}, -1);
if (lastIndex !== -1) {
console.log(`Last occurrence of '${substring}' found at index ${lastIndex}`);
} else {
console.log(`'${substring}' not found in the text.`);
}
OutputLast occurrence of 'example' found at index 51
Using indexOf() with a Loop
In this approach, we repeatedly use the indexOf method to find occurrences of the substring, starting the search just after the last found occurrence until no more occurrences are found. This way, we keep track of the last found index.
Example: This example demonstrates how to find the index of the last occurrence of a substring using indexOf in a loop.
JavaScript
function lastIndexOfSubstring(str, substring) {
let lastIndex = -1;
let currentIndex = -1;
while ((currentIndex = str.indexOf(substring, currentIndex + 1)) !== -1) {
lastIndex = currentIndex;
}
return lastIndex;
}
// Example usage:
let text = "This is a sample example of a sample example text example.";
let substring = "example";
console.log(lastIndexOfSubstring(text, substring)); // Output: 49
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read