RegEx to extract all matches from string using RegExp.exec

前端 未结 17 1193
-上瘾入骨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:21

    We are finally beginning to see a built-in matchAll function, see here for the description and compatibility table. It looks like as of May 2020, Chrome, Edge, Firefox, and Node.js (12+) are supported but not IE, Safari, and Opera. Seems like it was drafted in December 2018 so give it some time to reach all browsers, but I trust it will get there.

    The built-in matchAll function is nice because it returns an iterable. It also returns capturing groups for every match! So you can do things like

    // get the letters before and after "o"
    let matches = "stackoverflow".matchAll(/(\w)o(\w)/g);
    
    for (match of matches) {
        console.log("letter before:" + match[1]);
        console.log("letter after:" + match[2]);
    }
    
    arrayOfAllMatches = [...matches]; // you can also turn the iterable into an array
    

    It also seem like every match object uses the same format as match(). So each object is an array of the match and capturing groups, along with three additional properties index, input, and groups. So it looks like:

    [, , , ..., index: , input: , groups: ]
    

    For more information about matchAll there is also a Google developers page. There are also polyfills/shims available.

提交回复
热议问题