A string method to return all placements of a specified string?

我只是一个虾纸丫 提交于 2019-12-11 05:00:38

问题


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]


回答1:


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 ]



回答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"));



回答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:

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')
));


来源:https://stackoverflow.com/questions/44729417/a-string-method-to-return-all-placements-of-a-specified-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!