How to use the search() method In Javascript
Another approach for using regular expressions to determine the index of a substring’s first appearance is the search() method.
Example: Here is an example to find the index of the first occurrence of a substring in a string using the search() 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 index = originalString.search(regex);
console.log("Index of the first occurrence:", index);
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.