PDA

View Full Version : Enhanced version of String.format



r_honey
5 Aug 2011, 5:23 AM
I need an enhanced version of String.format, where {{0}} are not replaced (i.e. {{\d+}} is not replaced).
I have come up with the following code for the same:



format : function(format){
var args = Ext.toArray(arguments, 1);
return format.replace(/(\{(\d+)\})|(\{\{(\d+)\}\})/g, function(m, a, b, c, d) { if (m[0] == '{' && m[1] == '{') {
return (m);
} else {
return args[b];
}
});
}

Basically I have modified the regex adding an alternation construct for {{\d}} patterns, in the callback, if the match contains {{, then it is returned as is, otherwise its replaced.

Do you there is any problem with the above modifications (i.e. gotcha) or would it work fine?

I would have liked to do this with a pure regex (without the if-else in callback). .Net provides something called a Balancing pair construct, with which this could have been done in a pure Regex, I could not find a way to do it with constructs available in javascript regexes.