呈现多个Javascript变量的多个模板文字

问题描述 投票:0回答:1

我上面有以下代码,它们来自this answer,很遗憾,我没有必要的+50信誉才能在此处评论。

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

这非常适合一个变量,但不能与多个变量一起使用,这是我的意图,例如:

const interpolate = (str, obj) => str.replace(
  /\${([^}]+)}/g,
  (_, prop) => obj[prop]
);

const generatedText = "Hello ${Name}! your Mother ${Mother} is calling you!"; 
const Name = "Ana";
const Mother = "Miley";

console.log(interpolate(generatedText, { Name}, {Mother})); // Should print: Hello Ana! your Mother Miley is calling you!

这不起作用。

我一直在考虑使用forEach(),但不知道在这种情况下是否也无法使用。阅读有关map()的信息,但我只看到它用于var resultArr = array.map(function(x){return x.replace(REGULAREXPRESSION, newvalue);});之类的简单替换,它与替换模板文字的方式有所不同。

javascript str-replace template-literals
1个回答
1
投票

让传递给interpolate的第二个参数是具有多个属性

© www.soinside.com 2019 - 2024. All rights reserved.