JavaScript string format

has no built-in function to formatting strings, like C# string.Format(). This function solves the issue adding missing functionality.

In order to recognize string objects you should add a property to String prototype. You can find it in the code below isString. The usage of the function looks like this: “text {0}-{1}”.format(“blah1”, “blah2”) => “text blah1-blah2”

String.prototype.isString = true;
String.prototype.format = function () {
    var formatted = this;
    if (formatted.isString) {
        for (var i = 0; i < arguments.length; i++) {
            var regexp = new RegExp('\{' + i + '\}', 'gi');
            formatted = formatted.replace(regexp, arguments[i]);
        }
    }
    return formatted;
};

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Post

%d bloggers like this: