How to use RegExp and match() method In Javascript
The match() method of JavaScript can also be used to determine the index of the first instance of a substring when paired with regular expressions (RegExp).
Example: Here is an example to find the index of the first occurrence of a substring in a string using the RegExp and match() method
// Example string
const originalString = "This is a sample string";
// Target substring
const targetSubstring = "sample";
// Creating a regular expression dynamically
const regex = new RegExp(targetSubstring);
// Finding the index of the first occurrence
// of the target substring
const match = originalString.match(regex);
if (match) {
const index = match.index;
// Output: 21
console.log("Index of the first occurrence:", index);
} else {
console.log("Substring not found.");
}
Output
Index of the first occurrence: 10
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 constructing a website, working with data processing, or simply altering the text.
Contact Us