Stumbled upon (again) string format() discussion. This time on stackoverflow.com.
Basic idea is right. But none of the implementations was optimized enough. At least for me. None of the answers presented had no obvious optimization of using enclosure to initialize once and store regular expressions, for subsequent usages. Also, none of the examples respected format() implementation if one already exists.
Here is my version. Optimized.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// string.format function // (c) by dbj@dbj.org CC BY SA 4.0 // usage: "{0} means 'zero'".format("nula") returns: "nula means 'zero'" // place holders must be in a range 0-99. if no argument given for the placeholder, // no replacement will be done, so: "oops {99}".format("!"), returns the input // same placeholders will be all replaced with the same argument : // "oops {0}{0}".format("!","?") // returns "oops !!", arg 1 is not used. // if ("function" != typeof "".format) // add format() if one does not exist already String.prototype.format = (function() { // create once Regular Expressions to be used latter var rx1 = /\{(\d|\d\d)\}/g, rx2 = /\d+/ ; return function() { var args = arguments; return this.replace(rx1, function($0) { var idx = 1 * $0.match(rx2)[0]; return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : $0); }); } }()); alert("{0},{0},{{0}}!".format("{X}")); // |
This version also seems to be very robust.