RegEx to extract all matches from string using RegExp.exec

前端 未结 17 1497
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:49

I\'m trying to parse the following kind of string:

[key:\"val\" key2:\"val2\"]

where there are arbitrary key:\"val\" pairs inside. I want t

17条回答
  •  一个人的身影
    2020-11-22 03:01

    Since ES9, there's now a simpler, better way of getting all the matches, together with information about the capture groups, and their index:

    const string = 'Mice like to dice rice';
    const regex = /.ice/gu;
    for(const match of string.matchAll(regex)) {
        console.log(match);
    }
    

    // ["mice", index: 0, input: "mice like to dice rice", groups: undefined]

    // ["dice", index: 13, input: "mice like to dice rice", groups: undefined]

    // ["rice", index: 18, input: "mice like to dice rice", groups: undefined]

    It is currently supported in Chrome, Firefox, Opera. Depending on when you read this, check this link to see its current support.

提交回复
热议问题