Skip to content

Instantly share code, notes, and snippets.

@creage
Created April 25, 2014 20:45
Show Gist options
  • Save creage/11302690 to your computer and use it in GitHub Desktop.
Save creage/11302690 to your computer and use it in GitHub Desktop.
$.format
(function ($, window, document, undefined) {
$.extend({
/**
* Format at string using .NET C# syntax
$.format("test {0} and {1}", "is cool", "and passed");
$.format("test {1} and {0}", ["is cool", "and passed"]);
*/
format: (function () {
var iterate = function (txt, replacements) {
for (var i = 0, l = replacements.length; i < l; i++) {
txt = txt.replace(new RegExp("\\{" + (i) + "\\}", "g"), replacements[i]);
}
return txt;
};
return function () {
if (arguments.length) {
var args = arguments,
text = Array.prototype.splice.apply(args, [0, 1])[0];
if ($.isArray(args[0])) {
text = iterate(text, args[0]);
} else { // if first parameter is not an object it can be the first of a series of variant inline parameters.
text = iterate(text, args);
}
return text;
} else {
return this;
}
};
})()
});
}(jQuery, window, document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment