Is there a method like indexOf but that would return all placements of the specified string, in an array? Like "test test atest".method(test)
would return [0, 5, 11]
Asked
Active
Viewed 82 times
1

Procavia Capensis
- 17
- 3
-
Possible duplicate of [Finding all indexes of a specified character within a string](https://stackoverflow.com/questions/10710345/finding-all-indexes-of-a-specified-character-within-a-string) – mhodges Jun 23 '17 at 20:31
-
Some people misuse the `replace` method as follows: `let indices = []; "test test atest".replace(/test/g, (match, i) => indices.push(i));` – le_m Jun 23 '17 at 20:41
3 Answers
3
I'm not aware of such a method, but it's pretty easy to write using indexOf
:
function findAll(string, substring) {
var i = -1;
var indices = [];
while ((i = string.indexOf(substring, i+1)) !== -1) {
indices.push(i);
}
return indices;
}
console.log(findAll("test test atest", "test"));
// Output:
// [ 0, 5, 11 ]

user94559
- 59,196
- 6
- 103
- 103
1
You could use an custom prototype of string with iterating all results of String#indexOf
.
String.prototype.getIndicesOf = function (s) {
var result = [],
p= this.indexOf(s);
while (p !== -1) {
result.push(p);
p = this.indexOf(s, p + 1);
}
return result;
}
console.log("test test atest".getIndicesOf("test"));

Nina Scholz
- 376,160
- 25
- 347
- 392
0
Your question title specifically asks for a string method, and the technique below technically uses a RegExp method (where the string is, instead, a parameter of the method). However, it is fairly straightforward:
const regex = /test/g;
const indices = [];
while (result = regex.exec('test test atest')) indices.push(result.index);
console.log(JSON.stringify(indices));
It can also easily be converted into a nice, neat call-able function:
const findIndices = (target, query) => {
const regex = new RegExp(query, 'g');
const indices = [];
while (result = regex.exec(target)) indices.push(result.index);
return indices;
};
console.log(JSON.stringify(
findIndices('test test atest', 'test')
));

Andrew Willems
- 11,880
- 10
- 53
- 70