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 Index of Last Occurrence of Target Element in Sorted Array
In this article, we will see the JavaScript program to get the last occurrence of a number in a sorted array. We have the following methods to get the last occurrence of a given number in the sorted array. Methods to Find the Index of the Last Occurrence of the Target Element in the Sorted ArrayUsin
4 min read
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 Check Whether a String Starts and Ends With Certain Characters
In this article, We are going to learn how can we check whether a string starts and ends with certain characters. Given a string str and a set of characters, we need to find out whether the string str starts and ends with the given set of characters or not. Examples: Input: str = "abccba", sc = "a",
3 min read
JavaScript Program to Find iâth Index Character in a Binary String Obtained After n Iterations
Given a decimal number m, convert it into a binary string and apply n iterations. In each iteration, 0 becomes â01â and 1 becomes â10â. Find the (based on indexing) index character in the string after the nth iteration. Input: m = 5, n = 2, i = 3Output: 1Input: m = 3, n = 3, i = 6Output: 1Approach 1
6 min read
JavaScript Program to Print the First Letter of Each Word
Printing the first letter of each word involves extracting the initial character from every word in a given string, typically accomplished by splitting the string into words and selecting the first character from each resulting word. Examples of Printing the First Letter of Each Word Table of Conten
3 min read
JavaScript Program to find Lexicographically next String
In this article, we are going to learn how can we find the Lexicographically next string. Lexicographically next string refers to finding the string that follows a given string in a dictionary or alphabetical order. Examples: Input : testOutput : tesuExplanation : The last character 't' is changed t
3 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
Javascript Program To Find Length Of The Longest Substring Without Repeating Characters
Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
5 min read
How to Find and Replace All Occurrences of a Substring in a C++ String?
In C++, strings are sequences of characters that are used to represent textual data. In this article, we will learn how to find and replace all the occurrences of a particular substring in the given string. For Example, Input: str = "Lokesh is a good programmer, but Lokesh is still in the learning p
2 min read