How to use ES6’s includes() method In Javascript
The ES6 includes() method is mostly used to determine whether a string contains a particular substring, but with a little fiddling, it can also be used to get the index of the first occurrence.
Example: Here is an example to find the index of the first occurrence of a substring in a string using ES6’s includes() method.
// Example string
const originalString = "This is a sample string.";
// Target substring
const targetSubstring = "sample";
// Check if the target substring
// exists in the original string
const found = originalString.includes(targetSubstring);
if (found) {
const index = originalString.indexOf(targetSubstring);
// 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.