To find the indices of all occurrences of a substring in JavaScript, you can use a loop with the indexOf
method to find all occurrences and store their indices.
In this example,
str
with a string value.indexOf
method to find all occurrences of a specific substring within str
and store their indices in an array.let str = 'Hello Hello Hello';
let substr = 'Hello';
let indices = [];
let index = str.indexOf(substr);
while (index !== -1) {
indices.push(index);
index = str.indexOf(substr, index + 1);
}
console.log('Indices of all occurrences:', indices);
Indices of all occurrences: [ 0, 6, 12 ]
In this example,
str1
and str2
with different values.indexOf
method to find all occurrences of str2
within str1
and store their indices in an array.let str1 = 'apple banana cherry banana';
let str2 = 'banana';
let indices = [];
let index = str1.indexOf(str2);
while (index !== -1) {
indices.push(index);
index = str1.indexOf(str2, index + 1);
}
console.log('Indices of all occurrences:', indices);
Indices of all occurrences: [ 6, 20 ]
In this tutorial, we learned How to find the Indices of All Occurrences of Substring in JavaScript language with well detailed examples.