You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ES6字符串插值中t函数晚于字符串获取时的处理方案求助

解析含$t()插值的字符串

解决方案

不用eval,直接通过正则匹配插值格式,提取翻译键后调用t函数替换即可:

  1. 用正则表达式全局匹配所有$t(xxx)格式的插值片段
  2. 通过String.replace()的回调函数,将每个插值替换为t()的执行结果

修改后的代码

const mainFunction = (targetString) => {
    const { t } = getTranslationService();
    
    // 匹配$t(...)格式的插值,捕获括号内的翻译键
    return targetString.replace(/\$t\(([^)]+)\)/g, (_, translationKey) => {
        // 去除翻译键前后可能的空格,调用翻译函数
        return t(translationKey.trim());
    });
};

说明

  • 正则/\$t\(([^)]+)\)/g会匹配所有$t(...)结构,([^)]+)负责捕获括号内的翻译键(比如some.value)
  • 回调函数中直接调用t函数传入翻译键,返回的翻译结果会自动替换原插值部分
  • 支持同时处理多个插值,比如$t(hello) $t(world)会被正确替换

内容的提问来源于stack exchange,提问作者agusgambina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:10:36