Node.js自定义本地化字符串:如何动态替换占位符输出目标内容?
实现Node.js字符串本地化的占位符替换
你已经定义了多语言字符串模板,以下是几种实用的占位符替换实现方式:
方法1:简单单占位符替换
适合仅需替换{0}单个占位符的场景:
var globals = { enUS: { color:'color is {0}', cell:'cell phone' }, enGB: { color: 'colour is {0}', cell: 'mobile phone' } }; // 定义本地化替换函数 function getLocalizedString(key, lang, value) { return globals[lang][key].replace('{0}', value); } // 使用示例 console.log(getLocalizedString('color', 'enUS', 'blue')); // 输出: color is blue console.log(getLocalizedString('color', 'enUS', 'red')); // 输出: color is red console.log(getLocalizedString('color', 'enGB', 'blue')); // 输出: colour is blue
方法2:通用多占位符替换
如果后续需要支持多个占位符(如{0}、{1}),可以用正则实现更通用的格式化:
var globals = { enUS: { color:'color is {0}', greeting: 'Hi {0}, your favorite color is {1}' }, enGB: { color: 'colour is {0}', greeting: 'Hi {0}, your favourite colour is {1}' } }; // 通用字符串格式化函数 function formatTemplate(str, ...values) { return str.replace(/{(\d+)}/g, (match, index) => values[index] || match); } // 使用示例 console.log(formatTemplate(globals.enUS.color, 'blue')); // color is blue console.log(formatTemplate(globals.enUS.greeting, 'Alice', 'red')); // Hi Alice, your favorite color is red console.log(formatTemplate(globals.enGB.color, 'green')); // colour is green
方法3:封装成易用的本地化工具
可以把功能封装成工具类,方便切换语言和复用:
var globals = { enUS: { color:'color is {0}', cell:'cell phone', greeting: 'Hi {0}, your favorite color is {1}' }, enGB: { color: 'colour is {0}', cell: 'mobile phone', greeting: 'Hi {0}, your favourite colour is {1}' } }; const i18n = { currentLang: 'enUS', // 切换语言 setLanguage(lang) { if (globals[lang]) this.currentLang = lang; }, // 获取格式化后的本地化字符串 translate(key, ...values) { const template = globals[this.currentLang][key]; if (!template) return key; // 找不到模板时返回键名作为兜底 return template.replace(/{(\d+)}/g, (match, index) => values[index] || match); } }; // 使用示例 i18n.setLanguage('enUS'); console.log(i18n.translate('color', 'blue')); // color is blue console.log(i18n.translate('greeting', 'Bob', 'red')); // Hi Bob, your favorite color is red i18n.setLanguage('enGB'); console.log(i18n.translate('color', 'green')); // colour is green console.log(i18n.translate('cell')); // mobile phone
内容的提问来源于stack exchange,提问作者ursan526
相关产品推荐
相关产品推荐

