Ove*_*esh 21 javascript regex internationalization
在javascript中处理本地化字符串中的参数有什么好方法?我使用的格式与java的MessageFormat类相同,例如:
There are {0} apples in basket ID {1}.
凡{0}将与第一个参数,来代替{1}与第二.
这是我想在JS中使用的调用(即我想实现origStr):
var str = replaceParams(origStr, [5, 'AAA']);
我猜最好的策略是使用正则表达式.如果是这样,请提供良好的正则表达.但我很乐意听到其他任何选择.
str*_*ger 37
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);
Run Code Online (Sandbox Code Playgroud)
或者符合您的要求:
function replaceParams(string, replacements) {
return string.replace(/\{(\d+)\}/g, function() {
return replacements[arguments[1]];
});
// Or, if prototype code above...
String.format.apply(string, replacements);
}
Run Code Online (Sandbox Code Playgroud)
您可以添加花哨的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);
Run Code Online (Sandbox Code Playgroud)
Ale*_*ton 10
看起来我才迟到了大约3年,但是如果有人还需要JS的实际独立MessageFormat库:
https://github.com/SlexAxton/messageformat.js
你去吧!编译成JS - 所以它可以非常快速,并支持SelectFormat和PluralFormat.
注意::这是ICU MessageFormat,它与您的语言中可能包含的内容略有不同(读取:更好).