您如何将JavaScript变量转换为Template文字? [英] How would you turn a JavaScript variable into a Template literal?

查看:101
本文介绍了您如何将JavaScript变量转换为Template文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将生成并存储在字符串中的文本用作模板文字.

I would like to take text that I generated and stored in a string and use it like a template literal.

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!!!!.'

如何获取生成的文本成为模板字符串?

How can I get generated text to become a template string?

GeneratedText必须以变量开头,因此,我需要找到一种将其转换为模板字符串的方法.

generatedText must start in a variable so I need to find a way to convert it to a template string if possible.

我认为我不必说这个,但我也不想使用eval来冒险评估随机代码...

I didn't think I would have to put this but also I don't want to use eval to risk evaluating random code...

推荐答案

对于一般情况,您可以使用replacer函数用对象上的someProp属性替换每次出现的${someProp}:

For the general situation, you can use a replacer function to replace every occurrence of ${someProp} with the someProp property on an object:

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 }));

正则表达式\${([^}]+)}的意思是:

  • \$-文字$
  • {-文字{
  • ([^}]+)第一个(也是唯一一个)捕获组:
    • [^}]+-一个或多个不是}
    • 的字符
    • \$ - Literal $
    • { - Literal {
    • ([^}]+) First (and only) capture group:
      • [^}]+ - One or more characters which are not }

      由于prop是在方括号之间找到的属性名称,因此,用obj[prop]替换以所需的替换.

      Since prop is the property name found in between the brackets, replace with obj[prop] to replace with the desired replacement.

      这篇关于您如何将JavaScript变量转换为Template文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆