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

Render MULTIPLE Template Literals of Multiple Javascript variables

我上面有以下代码,来自:

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);}); 这样的简单替换,这与替换模板文字有很大不同。

让您传递给 interpolate 的第二个参数是具有 多个属性 单个对象 。每当您希望能够插入其他内容时,请向对象添加一个 属性(并向 generatedText 字符串添加一个 ${...}):

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!