JavaScript Program to find the Index of the First Occurrence of a Substring in a String
Last Updated :
17 Jun, 2024
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.
Methods to Find the Index of the First Occurrence of a Substring in a Given String:
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.
JavaScript
// 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);
OutputIndex of the first occurrence: 10
The match() method of JavaScript can also be used to determine the index of the first instance of a substring when paired with regular expressions (RegExp).
Example: Here is an example to find the index of the first occurrence of a substring in a string using the RegExp and match() method
JavaScript
// 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 match = originalString.match(regex);
if (match) {
const index = match.index;
// Output: 21
console.log("Index of the first occurrence:", index);
} else {
console.log("Substring not found.");
}
OutputIndex of the first occurrence: 10
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.
JavaScript
// 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.");
}
OutputIndex of the first occurrence: 10
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.
JavaScript
// 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);
OutputIndex of the first occurrence: 10
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.
JavaScript
// 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);
OutputIndex of the first occurrence: 10
Method 6: Using a Loop with substring() and indexOf() Methods
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.
JavaScript
// 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);
OutputIndex of the first occurrence: 10
Method 7: Using reduce() Method
This approach involves splitting the string at each occurrence of the target substring, then using the reduce()
method to find the cumulative length of the parts before the first occurrence. This length gives the index of the first occurrence of the substring.
Example:
This example demonstrates how to find the index of the first occurrence of a substring using the split()
and reduce()
methods.
JavaScript
// Example string
const originalString = "This is a sample string";
// Target substring
const targetSubstring = "sample";
// Function to find the index of the first occurrence
function findFirstOccurrenceIndex(str, substr) {
const parts = str.split(substr);
if (parts.length > 1) {
return parts.slice(0, -1).reduce((acc, part) => acc + part.length + substr.length, 0) - substr.length;
} else {
return -1; // Substring not found
}
}
const index = findFirstOccurrenceIndex(originalString, targetSubstring);
console.log("Index of the first occurrence:", index);
OutputIndex of the first occurrence: 10
Similar Reads
JavaScript Program to Find the First Repeated Word in String
Given a string, our task is to find the 1st repeated word in a string. Examples: Input: âRavi had been saying that he had been thereâOutput: hadInput: âRavi had been saying thatâOutput: No RepetitionBelow are the approaches to Finding the first repeated word in a string: Table of Content Using SetUs
4 min read
JavaScript Program to Find Kâth Non-Repeating Character in String
The K'th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K'th unique character encountered, it is returned as the result. This operation helps
6 min read
How to Replace the Last Occurrence of a Substring in a String in Java?
In this article, we will learn about replacing the last instance of a certain substring inside a string as a typical need. We'll look at a practical Java solution for this in this post. Replace the last occurrence of a Substring in a String in JavaWe may use the lastIndexOf() method to determine the
2 min read
Javascript Program To Check If A String Is Substring Of Another
Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :Â Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
2 min read
Shell Program to Find the Position of Substring in Given String
A string is made of many substrings or can say that if we delete one or more characters from the beginning or end then the remaining string is called substring. This article is about to write a shell program that will tell the position (index) of the substring in a given string. Let's take an exampl
7 min read
How to Replace the First Occurrence of a String Using Regex in Java?
Regex is a very interesting way to search for patterns in a String that the user provides. Regex stands for Regular Expressions. It consists of some patterns that can be planned and modified according to the usage of the program. In this article, we will discuss how to replace the first occurrence o
2 min read
Java Program to Find Occurrence of a Word Using Regex
Java's regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex. Program to Find Occurrence of a Word Using Re
2 min read
Which method returns the index within calling String object of first occurrence of specified value ?
In this article, we will know how to return the index of the first occurrence of the specified value(can be a string or character) in the string, also will understand their implementation through the examples. JavaScript indexOf() Method: The indexOf() method is a built-in & case-sensitive metho
3 min read
PHP Program To Check If A String Is Substring Of Another
Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1.Examples: Input: s1 = "for", s2 = "geeksforgeeks"Output: 5Explanation: String "for" is present as a substring of s2.Input: s1 = "practice", s2 = "geeksforgeeks"Output: -1.Ex
2 min read
How to get nth occurrence of a string in JavaScript ?
In this article, the task is to get the nth occurrence of a substring in a string with the help of JavaScript. We have many methods to do this some of which are described below:Approaches to get the nth occurrence of a string:Table of Content Using split() and join() methodsUsing indexOf() methodUsi
5 min read