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() MethodsThis 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
|