我想获取我生成并存储在字符串中的文本,并像模板文字一样使用它。
var generatedText = "Pretend this text was generated and then stored in a variable. ";
generatedText = "But I still need to use it as a template it to get ${variable}.";
var variable = "Successs!!!!";
console.log(generatedText);
//prints 'But I still need to interpolate it to get ${variable}.'
//how can I make it print using variable in it like a template as if it were doing this
console.log(`But I still need to use it as a template it to get ${variable}.`);
//prints 'But I still need to use it as a template it to get Successs!!!!.'
如何让生成的文本成为模板字符串?
generatedText 必须以变量开头,因此我需要找到一种方法将其转换为模板字符串(如果可能的话)。
编辑:
我认为我不必放这个,但我也不想使用 eval 来冒险评估随机代码...
最佳答案
对于一般情况,您可以使用替换函数将每次出现的 ${someProp}
替换为对象上的 someProp
属性:
const interpolate = (str, obj) => str.replace(
/\${([^}]+)}/g,
(_, prop) => obj[prop]
);
const generatedText = "But I still need to use it as a template it to get ${variable}.";
const variable = "Successs!!!!";
console.log(interpolate(generatedText, { variable }));
正则表达式\${([^}]+)}
表示:
\$
- 文字$
{
- 文字{
([^}]+)
第一个(也是唯一一个)捕获组:[^}]+
- 一个或多个不是 的字符
- 文字
}
由于 prop
是在括号之间找到的属性名称,因此替换为 obj[prop]
以替换为所需的替换项。
关于javascript - 您如何将 JavaScript 变量转换为模板文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57565794/