A String Method To Return All Placements Of A Specified String?
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]
Solution 1:
I'm not aware of such a method, but it's pretty easy to write using indexOf:
functionfindAll(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 ]Solution 2:
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"));Solution 3:
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:
constfindIndices = (target, query) => {
  const regex = newRegExp(query, 'g');
  const indices = [];
  while (result = regex.exec(target)) indices.push(result.index);
  return indices;
};
console.log(JSON.stringify(
  findIndices('test test atest', 'test')
));
Post a Comment for "A String Method To Return All Placements Of A Specified String?"