How to use ES6’s findIndex() method In Javascript
The index of the first instance of a substring can be discovered using the array’s findIndex() method. But first, the string must be turned into a character array.
Example: Here is an example to find the index of the first occurrence of a substring in a string using ES6’s findIndex() method.
// Example string
const originalString = "This is a sample string.";
// Target substring
const targetSubstring = "sample";
// Convert the string into an array of characters
const charArray = Array.from(originalString);
// Finding the index of the first occurrence
// of the target substring
const index = charArray.findIndex(
(_, i) =>
originalString.slice(
i,
i + targetSubstring.length
) === targetSubstring
);
// Output: 21
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.
Contact Us