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.'