Better solution to assign regex.exec () during loop

Is there a better solution for this here? I try to avoid assignment internally while

, but can still loop through matches and use 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've added a little more context to this question, as well as a RegEx example.

+3


source to share


5 answers


I always do the following when I need to .exec

:

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

      



Regular expressions with a flag g

have an infinite effect when it is in a looping state.

What is the difference between Fx 3.x and Fx 4.x that caused many custom scripts to stop working?

+2


source


If you want to avoid assignment internally while

, you can use a loop do while

:

var URLRegExp = /url\s*\(\s*["|']?(.*?)\s*["|']?\)\s*/g
var match
do {
  match = URLRegExp.exec(bootstrap)
  if (match) {
    // Do stuff here per match...
  }
} while (match)

      



But a while loop

it is simpler and avoids unnecessary code like operator if

inside do

. Assigning within a condition isn't as bad as people think, as long as you understand what the behavior of the code is and what the context is.

Another case is when you use linter to avoid the error of a comparison operator (like ==) as an assignment operator, but all of the above all linters used support using comments to change the Linter behavior in a certain part of the code, so this is not a problem.

+2


source


var match = "Is This The Real Life|Is This Just Fantasy|Caught In A Landslide|No Escape From Reality|".match(/.+?\|/ig);

//print result using join
document.body.innerHTML += match.join("<br />");
document.body.innerHTML += "<br /><br />";
//print results using for loop and strip |
for (var i = 0; i < match.length; ++i)
{
    document.body.innerHTML += match[i].slice(0, -1) + "<br />";
}
      

Run code


This will avoid the loop completely. match

returns an array. You can loop over it and do something with it, or as if I were printing out the results using join. match

accepts regex-patterns

.

0


source


var matches = someString.match(REGEX_PATTERN);
for (var i = 0; matches && i < matches.length; i++) {
  // Do stuff here per match…
}

      

0


source


someString.replace(REGEX_PATTERN,
    function (wholeMatch, group1, group2/*...*/, index, sourceString) {
        // Do stuff here per match…
    });

      

0


source







All Articles