Help with efficient RegExp replace() loop

W

Will

I have the following code:

var rx = /{{(.+?)}}/i;
var expr = 'each {{word}} wrapped in {{curly}} {{braces}} in this
{{string}} needs to be {{replaced}} with a different {{value}}.';
var values = [];
values["value"] = "foo";
values["string"] = "bar";
values["braces"] = "bundy";

while(expr.match(rx)) {
expr = expr.replace(rx, values[RegExp.$1]);
}

Can anyone suggest a more efficient way of writing the match/replace
loop. Is there any way to do it with a single replace() call only?

Please note that I'm looking solely at improving the efficiency of the
while() loop. The actual input string and array of values are
irrelevant and for demonstration purposes only.

TIA

Will
 
L

Lasse Reichstein Nielsen

I have the following code:

var rx = /{{(.+?)}}/i;
var expr = 'each {{word}} wrapped in {{curly}} {{braces}} in this
{{string}} needs to be {{replaced}} with a different {{value}}.';

Don't wrap code lines when posting. If your client can't avoid it,
make sure your lines are no longer than ~72 characters.
var values = [];
values["value"] = "foo";
values["string"] = "bar";
values["braces"] = "bundy";

You should use an object, not an array, for values. I.e.,
var values = {};
since you don't use the "arrayness" at all.
while(expr.match(rx)) {
expr = expr.replace(rx, values[RegExp.$1]);
}
Can anyone suggest a more efficient way of writing the match/replace
loop. Is there any way to do it with a single replace() call only?

expr = expr.replace(/\{\{(.+?)}}/g,function(match,word){
return values[word] || "";
});


Remember that "{" is also special in regexps.

The || "" is for words that are not in the values dictionary. It returns
the empty string for those.
Please note that I'm looking solely at improving the efficiency of the
while() loop.

I don't know if it is more efficient, but it is slightly shorter. :)

Not all versions of Javascript allow a function as second argument, but
since you use the non-greedy match (.+?), which is also only in modern
browsers, I don't think it is a problem (i.e., if it fails, so does the
non-greedy match).

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,276
Latest member
Sawatmakal

Latest Threads

Top