MessageFormat in javascript (parameters in localized UI strings)

Viewed 15485

What is a good way for handling parameters in localized strings in javascript? I am using the same format as in java's MessageFormat class, e.g.:

There are {0} apples in basket ID {1}.

Where {0} will be replaced with the first parameter and {1} with the second.

This is the call I want to use in JS (i.e. I want to implement origStr):

var str = replaceParams(origStr, [5, 'AAA']);

I am guessing the best strategy would be to use a regular expression. If so, please offer a good regular expression. But I'm open to hear any other options.

3 Answers

@strager answer did not really work for me, but with a little tweak i got it to be just what i was looking for (which is very similar to what @Omesh was aiming to).

String.prototype.format = function() {
    var args = arguments;

    return this.replace(/\{(\d+)\}/g, function(a) {
        return args[0][parseInt(a.match(/(\d+)/g))];
    });
};

Notice the index value of the args array is different.

It should be called just like @strager suggests:

'I like {0} and {1} but not {2}'.format('apples', 'oranges', 'kiwi');
Related