RegEx to extract all matches from string using RegExp.exec

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

    Based on Agus's function, but I prefer return just the match values:

    var bob = "> bob <";
    function matchAll(str, regex) {
        var res = [];
        var m;
        if (regex.global) {
            while (m = regex.exec(str)) {
                res.push(m[1]);
            }
        } else {
            if (m = regex.exec(str)) {
                res.push(m[1]);
            }
        }
        return res;
    }
    var Amatch = matchAll(bob, /(&.*?;)/g);
    console.log(Amatch);  // yeilds: [>, <]
    

提交回复
热议问题