Replicating c# String.Format with JavaScript

I was getting really sick of not having a way to populate placeholder text in JavaScript so i took 5 minutes out to write a small script to replicate the functionality in c#.

The code below is an initial prototype and does not have any validation etc. but i wanted to get something down.

See it working on JSFiddle

Feel free to use or alter this in your own work.

if (!String.prototype.stringFormat) {
String.prototype.stringFormat = function() {

var initialString = this.valueOf();
for (var i = 0, maxlength = arguments.length; i < maxlength; i++) {

var indexStr = '{'+ i + '}';
initialString = initialString.replace(indexStr, arguments[i]);
};
return initialString;
}
};

Advertisements
Posted in Mad ramblings

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: