Journal of a software dev

October 30, 2011

Replicating String.Format() in Javascript

Filed under: javascript — Tags: , , , , , — Michael Cromwell @ 9:42 pm

One of the annoying issues with Javascript is when it comes to formatting strings with values from variables usually you end up with the following:

var someValue = 100;
var anotherValue = 555;
alert('someValue is ' + someValue + ' and anotherValue is ' + anotherValue);

This ends up being hard to read and also prone to errors when operators/quotes are missed or not matched properly, if this was C# we could do the following:

var someValue = 100;
var anotherValue = 555;
Console.WriteLine(String.Format("someValue is {0} and anotherValue is {1}", someValue, anotherValue));

This is much nicer it would be better if we had string interpolation but hey-ho maybe in a future version.

One of the great things about the dynamic nature of Javascript is that you can extend any of it’s types as they are all objects using the prototype keyword, so we can extend the String object and also make use of the arguments object to allow any number parameters to be passed in:

String.prototype.format = function()
{
   var content = this;
   for (var i=0; i < arguments.length; i++)
   {
        var replacement = '{' + i + '}';
        content = content.replace(replacement, arguments[i]);  
   }
   return content;
};

This allows us to replace the first code example with this:

var someValue = 100;
var anotherValue = 555;
alert('someValue is {0} and anotherValue is {1}'.format(someValue, anotherValue));

Which I think reads better than the static Format method as C# does not have built-in support for doing the following "test {0}".Format(123).

Advertisement

1 Comment »

  1. There is also String.format in the MicrosoftAjax.js.

    Comment by Anonymous — November 5, 2011 @ 6:59 pm


RSS feed for comments on this post. TrackBack URI

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 )

Connecting to %s

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.