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
JavaScript Program to find the Index of the First Occurrence of a Substring in a String In this article, we will find the index of the first occurrence of a substring in a string using JavaScript. An essential task in JavaScript programming is searching for substrings within a string. Finding the index of the first occurrence of a substring is a typical necessity, whether you are const
6 min read
How to Replace the Last Occurrence of a Substring in a String in Java? In this article, we will learn about replacing the last instance of a certain substring inside a string as a typical need. We'll look at a practical Java solution for this in this post. Replace the last occurrence of a Substring in a String in JavaWe may use the lastIndexOf() method to determine the
2 min read
Javascript Program To Check If A String Is Substring Of Another Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :Â Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
2 min read
Shell Program to Find the Position of Substring in Given String A string is made of many substrings or can say that if we delete one or more characters from the beginning or end then the remaining string is called substring. This article is about to write a shell program that will tell the position (index) of the substring in a given string. Let's take an exampl
7 min read
Java Program to Find Occurrence of a Word Using Regex Java's regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex. Program to Find Occurrence of a Word Using Re
2 min read
How to find the last index using regex of a particular word in a String? To find the last index of a particular word in a string using regular expressions in Java, you can use the Matcher class along with a regular expression that captures the desired word. Java Program to last index Using the Regex of a Particular Word in a StringBelow is the implementation of the last
2 min read
Which method returns the index within calling String object of first occurrence of specified value ? In this article, we will know how to return the index of the first occurrence of the specified value(can be a string or character) in the string, also will understand their implementation through the examples. JavaScript indexOf() Method: The indexOf() method is a built-in & case-sensitive metho
3 min read
Find the Index of a Substring in Python Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python.Using str.find() The find() method searches for the first occurrence of the specified substring and return
3 min read
How to Split a String into Equal Length Substrings in Java? In Java, splitting a string into smaller substrings of equal length is useful for processing large strings in manageable pieces. We can do this with the substring method of the loop. This method extracts a substring of the specified length from the input string and stores it in a list.Example:In the
3 min read
Java Program to Search a Particular Word in a String Using Regex In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings. In this article, we will learn how to search for a particular word in a
3 min read