Skip to content

Instantly share code, notes, and snippets.

@dotnetCarpenter
Created February 21, 2011 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotnetCarpenter/836756 to your computer and use it in GitHub Desktop.
Save dotnetCarpenter/836756 to your computer and use it in GitHub Desktop.
nice C# like formattin structure in js
/**
* Format all arguments into the first argument. This is a
* convenience function similar to the C sprintf function, though
* only with simple replacements. Replacements are formatted like
* #{i} where i is a zero based index into the additional
* arguments passed in to format beyond the first.
*
* Additional parameters not used will be ignored.
*
* Including formatting requests for parameters that don't exist
* will throw an exception.
*
* The first argument must be the string that needs to be
* formatted. Additional arguments are formatted into that
* string.
*
* If any of the arguments to the format string include a string
* that matches the #{i} format, the result could be erroneous.
*
* Example: $.guards.format("#{2} #{0} #{1}", "hello", "world", 3); // "3 hello world"
* Example: $.guards.format("#{0} #{1}", "hello", "world", 3); // "hello world".
* Example: $.guards.format("#{2} #{0} #{1}", "hello", "world"); // throws exception
*/
$.Guards.prototype.format = function() {
var str = arguments[0];
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
var regex = "\\#\\{" + (i - 1) + "\\}";
str = str.replace(new RegExp(regex, "g"), arguments[i]);
}
}
if (/\#\{\d+\}/.test(str)) {
throw new Error("Unmatched formatting found!");
}
return str;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment