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

后端 未结 6 483
轮回少年
轮回少年 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:33

    You could use / abuse the replace function:

    var result = [];
    "abcdab".replace(/(a)/g, function (a, b, index) {
        result.push(index);
    }); 
    result; // [0, 4]
    

    The arguments to the function are as follows:

    function replacer(match, p1, p2, p3, offset, string) {
      // p1 is nondigits, p2 digits, and p3 non-alphanumerics
      return [p1, p2, p3].join(' - ');
    }
    var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
    console.log(newString);  // abc - 12345 - #$*%
    

提交回复
热议问题