22

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.

1

3 Answers 3

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

    return this.replace(/\{(\d+)\}/g, function() {
        return args[arguments[1]];
    });
};

// Returns '2 + -1 = 1'.
'{0} + {1} = {2}'.format(2, -1, 1);

Or to fit your requirement:

function replaceParams(string, replacements) {
    return string.replace(/\{(\d+)\}/g, function() {
        return replacements[arguments[1]];
    });

    // Or, if prototype code above...
    String.format.apply(string, replacements);
}

You can add fancy i18n features such as ordinal-i-fying (whatever it's called):

// Not well tested.

i18n.en.filters = {
    ordinal: function(n) {
        // FIXME Doesn't handle all cases.
        switch(('' + n).substr(-1)) {
            case '1':
                return '' + n + 'st';
            case '2':
                return '' + n + 'nd';
            case '3':
                return '' + n + 'rd';
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case '0':
                return '' + n + 'th';
            default:
                return n; // Just in case...
        }

    },
    plural: function(n, singular, plural) {
        if(n == 1) {
            return singular;
        } else {
            return plural;
        }
    }
};

i18n.current = i18n.en;

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

    return this.replace(/\{((\d+)((\|\w+(:\w+)*)*))\}/g, function() {
        var arg = args[arguments[2]],
            filters = arguments[3].split('|'),
            i, curFilter, curFilterArgs, curFilterFunc;

        for(i = 0; i < filters.length; ++i) {
            curFilterArgs = filters[i].split(':');
            curFilter = curFilterArgs.shift();
            curFilterFunc = i18n.current.filters[curFilter];

            if(typeof curFilterFunc === 'function') {
                arg = curFilterFunc.apply(null, [ arg ].concat(curFilterArgs));
            }
        }

        return arg;
    });
};

'You have {0} {0|plural:cow:cows} but I have {1} {1|plural:cow:cows}.'.format(2,1);
'My horse came in {0|ordinal} place while yours came in {1|ordinal}.'.format(42,1);
10

Looks like I was only about 3 years late, but in case anyone still needs an actual standalone MessageFormat library for JS:

https://github.com/SlexAxton/messageformat.js

There ya go! Compiles to JS - so it can be really speedy, and supports SelectFormat and PluralFormat.

Note:: This is ICU MessageFormat which is a bit different (read: better) than the stuff that might be built into your language.

4
  • Gotta say, this is a little different to what I expected. We use ICU MessageFormat in Java, and it looks more like {0,plural, zero{no results} one{1 result} other{{0} results}}. Whereas this one looks like {RES, plural, =0{no results} one{1 result} other{# results} } - other than superficially using the same CLDR keywords for one/other/etc. it seems like a completely different format to me.
    – Hakanai
    Dec 22, 2016 at 3:05
  • MessageFormat.js and MessageFormat.java only happen to share names. The syntax is completely different.
    – Dean Moses
    Sep 17, 2017 at 7:30
  • 1
    They're the same format, and are mostly compatible with each other actually. The two examples @Trejkaz mention there only differ in which keywords are being used. =0 is a literal value, where zero is a keyword (that doesn't apply to en-US). Oct 20, 2017 at 7:50
  • "Doesn't apply", but works totally fine as far as we can tell, and is useful for differentiating messages when talking about "no things".
    – Hakanai
    Oct 20, 2017 at 23:38
1

@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');

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.