简体   繁体   English

javascript中的MessageFormat(本地化UI字符串中的参数)

[英]MessageFormat in javascript (parameters in localized UI strings)

What is a good way for handling parameters in localized strings in javascript? 在javascript中处理本地化字符串中的参数有什么好方法? I am using the same format as in java's MessageFormat class, eg: 我使用的格式与java的MessageFormat类相同,例如:

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

Where {0} will be replaced with the first parameter and {1} with the second. 其中{0}将替换为第一个参数, {1} {0}将替换为第二个参数。

This is the call I want to use in JS (ie I want to implement origStr ): 这是我想在JS中使用的调用(即我想实现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. 但我很乐意听到其他任何选择。

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): 您可以添加花哨的i18n功能,例如序数i-fying(无论它叫什么):

// 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);

Looks like I was only about 3 years late, but in case anyone still needs an actual standalone MessageFormat library for JS: 看起来我才迟到了大约3年,但是如果有人还需要JS的实际独立MessageFormat库:

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

There ya go! 你去吧! Compiles to JS - so it can be really speedy, and supports SelectFormat and PluralFormat . 编译为JS - 因此它可以非常快速,并支持SelectFormatPluralFormat

Note:: This is ICU MessageFormat which is a bit different (read: better) than the stuff that might be built into your language. 注意::这是ICU MessageFormat,它与您的语言中可能包含的内容略有不同(读取:更好)。

@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). @strager的答案对我来说并没有真正起作用,但通过一些调整我得到的就是我正在寻找的东西(这与@Omesh的目标非常相似)。

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. 请注意,args数组的索引值是不同的。

It should be called just like @strager suggests: 它应该像@strager建议一样调用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM