Search code examples
javascriptregex

Better solution to regex.exec() assignment in while loop


Is there any better solution to this here? I try to avoid the assignment inside while but still be able to loop through the matches and use the captured groups.

var match = "";
var CSS_URL_PATTERN = /url\s*\(\s*["|']?(.*?)\s*["|']?\)\s*/gm
while ((match = CSS_URL_PATTERN.exec(someBigCSSString)) !== null) {
   // Do stuff here per match…
}

I added a bit more context to this question, also a RegEx example.


Solution

  • I always do as follows when I need .exec:

    var re = /.../g, match;
    while (match = re.exec(...)) {
        //...
    }
    

    Regular expressions with g flag causes infinite effect when it is in the loop condition.

    What are the differences between Fx 3.x and Fx 4.x that made many userscripts stop working?