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

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

    You can get all match indexes like this:

    var str = "abcdab";
    var re = /a/g;
    var matches;
    var indexes = [];
    while (matches = re.exec(str)) {
        indexes.push(matches.index);
    }
    // indexes here contains all the matching index values
    

    Working demo here: http://jsfiddle.net/jfriend00/r6JTJ/

提交回复
热议问题