问题
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 must start in a variable so I need to find a way to convert it to a template string if possible.
Edit:
I didn't think I would have to put this but also I don't want to use eval to risk evaluating random code...
回答1:
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 }));
The regular expression \${([^}]+)}
means:
\$
- Literal$
{
- Literal{
([^}]+)
First (and only) capture group:[^}]+
- One or more characters which are not}
}
- Literal}
Since prop
is the property name found in between the brackets, replace with obj[prop]
to replace with the desired replacement.
回答2:
The interpolate
function below is an extended version of this answer that adds support for simple nested object field references (e.g.: a.b.c
)
function interpolate(s, obj) {
return s.replace(/[$]{([^}]+)}/g, function(_, path) {
const properties = path.split('.');
return properties.reduce((prev, curr) => prev && prev[curr], obj);
})
}
console.log(interpolate('hello ${a.b.c}', {a: {b: {c: 'world'}}}));
// Displays 'hello world'
回答3:
You should emulate a template literal instead, because letting text from ~somewhere~ run arbitrary JavaScript like a real template literal’s ${}
sections can usually isn’t a good idea:
generatedText.replace(/\$\{variable}/g, variable);
来源:https://stackoverflow.com/questions/57565794/how-would-you-turn-a-javascript-variable-into-a-template-literal