I\'m looking for a good JavaScript equivalent of the C/PHP printf()
or for C#/Java programmers, String.Format()
(IFormatProvider
for .
For use with jQuery.ajax() success functions. Pass only a single argument and string replace with the properties of that object as {propertyName}:
String.prototype.format = function () {
var formatted = this;
for (var prop in arguments[0]) {
var regexp = new RegExp('\\{' + prop + '\\}', 'gi');
formatted = formatted.replace(regexp, arguments[0][prop]);
}
return formatted;
};
Example:
var userInfo = ("Email: {Email} - Phone: {Phone}").format({ Email: "someone@somewhere.com", Phone: "123-123-1234" });