RegEx to extract all matches from string using RegExp.exec

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

    If you have ES9

    (Meaning if your system: Chrome, Node.js, Firefox, etc supports Ecmascript 2019 or later)

    Use the new yourString.matchAll( /your-regex/ ).

    If you don't have ES9

    If you have an older system, here's a function for easy copy and pasting

    function findAll(regexPattern, sourceString) {
        let output = []
        let match
        // make sure the pattern has the global flag
        let regexPatternWithGlobal = RegExp(regexPattern,[...new Set("g"+regexPattern.flags)].join(""))
        while (match = regexPatternWithGlobal.exec(sourceString)) {
            // get rid of the string copy
            delete match.input
            // store the match data
            output.push(match)
        } 
        return output
    }
    

    example usage:

    console.log(   findAll(/blah/g,'blah1 blah2')   ) 
    

    outputs:

    [ [ 'blah', index: 0 ], [ 'blah', index: 6 ] ]
    

提交回复
热议问题