String.format for javascript (C# .NET like syntax for concatenating strings)

Here is a little hack to make javascript behave more like .NET with string.format…

usage:

var selector = String.format("#container{0} div.lineItem{1}[data-entryid='{2}']", containerId, itemId, entryId);

js code:

//String.format for js.
if (!String.format) {
String.format = function (format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}

From: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4673436#4673436

Leave a Reply

Your email address will not be published. Required fields are marked *