By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,780 Members | 1,126 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,780 IT Pros & Developers. It's quick & easy.

Help with efficient RegExp replace() loop

P: n/a
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
Jul 20 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
in**@whawes.co.uk (Will) writes:
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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.