How to use Regular Expression In Javascript
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.
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.`);
};
Output
Last occurrence of ' sample ' found at index 45
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