【发布时间】:2019-12-12 06:13:10
【问题描述】:
我们有一个我们编写的翻译提取工具,它可以提取我们在 TypeScript 中标记为翻译的字符串。 JavaScript 工具读取我们的 Typescript 文件并具有如下正则表达式:
fileContent.match(/this.\translate\((.*?));/);
(为了可读性而简化,这工作正常)
翻译方法有3个参数:1.要翻译的字符串,2.可能被插值的任何变量,3.描述。最后两个是可选的。 实现示例:
this.translate('text to translate');
this.translate('long text' +
'over multiple lines');
this.translate(`text to translate with backticks for interpolation`);
this.translate(`some test with a ${variable}`, [variable]);
this.translate(`some test with a ${variable}`, [variable], 'Description');
我们需要从 JavaScript 中的文本中提取这 3 个参数,并且在解析它时遇到了问题。我们目前正在使用正则表达式来检查第一个开始字符串字符(' 或“`”)并尝试匹配结束字符,但这很难做到。
我目前正在尝试使用eval(该脚本不在浏览器中运行,而是在 CLI 中运行),如下所示:
function getParameters(text, variables, description){
return {text: text, variables: variables, description: description}
}
toEval = string.replace('this.translate', 'getParameters');
eval(toEval);
如果没有变量,这很完美,但是当我们传入变量时会抱怨"variables" not defined。
任何人都可以提出一个好的/更好的方法来处理这个文本提取吗?
【问题讨论】:
标签: javascript regex string typescript extraction