How to usea Loop with substring() and indexOf() Methods in Javascript
This method involves iterating through the string and using the substring method to compare slices of the original string with the target substring.
Example: Here is an example to find the index of the first occurrence of a substring in a string using a loop with the substring() and indexOf() methods.
// Example string
const originalString = "This is a sample string";
// Target substring
const targetSubstring = "sample";
// Finding the index of the first occurrence of the target substring using a loop
let index = -1;
for (let i = 0; i <= originalString.length - targetSubstring.length; i++) {
if (originalString.substring(i, i + targetSubstring.length) === targetSubstring) {
index = i;
break;
}
}
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.