Equivalent of String.format in jQuery
I'm trying to move some JavaScript code from MicrosoftAjax to JQuery. I use the JavaScript equivalents in MicrosoftAjax of the popular .net methods, e.g. String.format(), String.startsWith(), etc. Are there equivalents to them in jQuery?
Solution 1:
The source code for ASP.NET AJAX is available for your reference, so you can pick through it and include the parts you want to continue using into a separate JS file. Or, you can port them to jQuery.
Here is the format function...
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
And here are the endsWith and startsWith prototype functions...
String.prototype.endsWith = function (suffix) {
return (this.substr(this.length - suffix.length) === suffix);
}
String.prototype.startsWith = function(prefix) {
return (this.substr(0, prefix.length) === prefix);
}
Solution 2:
This is a faster/simpler (and prototypical) variation of the function that Josh posted:
String.prototype.format = String.prototype.f = function() {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
Usage:
'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7)
I use this so much that I aliased it to just f
, but you can also use the more verbose format
. e.g. 'Hello {0}!'.format(name)