1

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?

1
  • a. The first index is 0, not 1. b. You should replace the whole {..} thing, not just the number. c. you never modify text, you never do anything with result, you never return anything. d. I can't even imagine what you think arguments["$1"] means. Commented Jul 11, 2014 at 18:30

1 Answer 1

2

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"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.