Marcelo Camargo
Marcelo Camargo

Reputation: 2298

string.Format in JS

I'm trying to simulate the C# string.Format() in JS.

For this, I have an object called string and a function called Format() passing as parameter, in a variadic function, a string with its placeholders and also its values.

An example should be:

string.Format("{0} - {1}", "Hello", "World");

that must return me Hello - World.

Although, it gives me just "{undefined} - {undefined}". I'm using global modifier to get all, but it doesn't works.


var string = {
    Format: function() {
        var text = arguments[0];
        for (i = 1; i < arguments.length; i++) {
            var result = text.replace(/([0-9]+)/g, arguments["$1"]);
        }
        console.log(result);
    }
}

Where is my error?

Upvotes: 1

Views: 188

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382304

You're always starting from the initial string (ignoring the previous replacements) and there are parts of you're function where it's unclear how it's supposed to work.

Here's a working implementation based on your general idea :

var string = {
  Format: function() {
    var args = arguments,
        result = args[0].replace(/([0-9]+)/g, function(s) { return args[+s+1] });
    console.log(result);
    return result;
  }
}

It logs "{Hello} - {World}"

Now, supposing you don't want to keep the braces and you also want to ensure you only replace numbers between braces, you can do this (without the debug logging) :

var string = {
    Format: function() {
        var args = arguments;
        return args[0].replace(/{([0-9]+)}/g, function(s) {
            return args[+s.slice(1,-1)+1]
        });
    }
}

It returns "Hello - World"

Upvotes: 2

Related Questions