Blog

Blogging on programming and life in general.

String.Format In JavaScript

Posted in: Client-side

Whenever I work with strings whilst programming in .NET, somewhere along the lines I always find myself using the awesome “string.format”. I think all of you will admit its the most useful and easiest way to build up your strings.

The only downside to using the “string.format” method is that it lures you into a false sense of security and you find yourself lost without it when it comes to working with strings in other languages. This happened to me when I had to build up a long string in JavaScript. It was long and tedious…or maybe I am just lazy.

Luckily, there have been a few developers who extended the string object in JavaScript to include “string.format”. Amazing! Its goes along the lines of adding this to your own JavaScript code:

String.format = String.prototype.format = function() {
    var i=0;
    var string = (typeof(this) == “function” && !(i++)) ? arguments[0] : this;

    for (; i < arguments.length; i++)
        string = string.replace(/\{\d+?\}/, arguments[i]);

    return string;
}

Here are some other useful links I have found on how to implement “string.format” into your JavaScript code:

blog comments powered by Disqus
;