Javascript Regexp loop all matches

前端 未结 6 1931
名媛妹妹
名媛妹妹 2021-02-06 22:16

I\'m trying to do something similar with stack overflow\'s rich text editor. Given this text:

[Text Example][1]

[1][http://www.example.com]

I

6条回答
  •  执念已碎
    2021-02-06 22:29

    Another way to iterate over all matches without relying on exec and match subtleties, is using the string replace function using the regex as the first parameter and a function as the second one. When used like this, the function argument receives the whole match as the first parameter, the grouped matches as next parameters and the index as the last one:

    var text = "[Text Example][1]\n[1][http: //www.example.com]";
    // Find resource links
    var arrMatch = null;
    var rePattern = new RegExp("\\[(.+?)\\]\\[([0-9]+)\\]", "gi");
    text.replace(rePattern, function(match, g1, g2, index){
        // Do whatever
    })
    

    You can even iterate over all groups of each match using the global JS variable arguments, excluding the first and last ones.

提交回复
热议问题