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

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

    If you only want to find simple characters, or character sequences, you can use indexOf [MDN]:

    var haystack = "abcdab",
        needle = "a"
        index = -1,
        result = [];
    
    while((index = haystack.indexOf(needle, index + 1)) > -1) {
        result.push(index);
    }
    

提交回复
热议问题