How to use the indexOf() method In Javascript
The index of the first occurrence of a given substring can be obtained for strings using the built-in method indexOf() provided by JavaScript. The basic syntax of indexOf() is as follows.
Example: Here is an example to find the index of the first occurrence of a substring in a string using the indexOf() method.
// 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
const index = originalString.indexOf(targetSubstring);
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.