C. Morgan C. Morgan - 1 month ago 17
Javascript Question

Weird replace behavior

I have tried creating a String.format function in JS like C# so I don't have to do

foo + ", " + bar
and do
"{0}, {1}".format(foo, bar);
I have got some pretty good results with this only using
{0}
.

String.prototype.format = function() {
var replacement = "";

for (var i = 0; i < arguments.length; i++) {
replacement += this.replace("{" + i + "}", arguments[i]);
}

return replacement;
};


Except doing
"{0} {1}".format("foo", "bar");
comes out with:
foo {0}{1} bar
or a SyntaxError. I have never had any errors with replace like this before though.

Answer

I think this will help you.

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