How to get all indexes of a pattern in a string?

后端 未结 6 504
轮回少年
轮回少年 2021-01-18 19:56

I want something like this:

\"abcdab\".search(/a/g) //return [0,4]

Is it possible?

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 20:43

    You can use the RegExp#exec method several times:

    var regex = /a/g;
    var str = "abcdab";
    
    var result = [];
    var match;
    while (match = regex.exec(str))
       result.push(match.index);
    
    alert(result);  // => [0, 4]
    

    Helper function:

    function getMatchIndices(regex, str) {
       var result = [];
       var match;
       regex = new RegExp(regex);
       while (match = regex.exec(str))
          result.push(match.index);
       return result;
    }
    
    alert(getMatchIndices(/a/g, "abcdab"));
    

提交回复
热议问题