Replicating String.Format() in Javascript

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).


3 thoughts on “Replicating String.Format() in Javascript

  1. With havin so much content do you ever run into any problems
    of plagorism or copyright infringement? My blog
    has a lot of completely unique content I’ve either authored myself or outsourced but it seems a lot of it is popping it up all over the web without my permission. Do you know any solutions to help reduce content from being stolen? I’d
    truly appreciate it.

  2. Attractive section of content. I just stumbled upon your site and in accession capital to assert that I get
    actually enjoyed account your blog posts. Anyway I will be subscribing to your feeds and even I achievement you access consistently fast.

Comments are closed.