【问题标题】:Render MULTIPLE Template Literals of Multiple Javascript variables渲染多个 Javascript 变量的多个模板文字
【发布时间】:2019-12-31 07:44:21
【问题描述】:

我上面有以下代码,来自this answer

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

这完全适用于 ONE 变量,但不适用于多个变量,这是我的意图,例如:

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】:

    让您传递给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!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 2017-11-27
      • 2017-11-06
      相关资源
      最近更新 更多