模板字符串插值

javascript/exercises/interpolate2026-08-24 19:46:25

问题

const template =
  "The sum of {{ a }} and {{ b }} is {{ a + b }} and the product is {{ a * b }}.";
const data = { a: 5, b: 3 };

const result = interpolate(template, data);
console.log(result); // 输出: "The sum of 5 and 3 is 8 and the product is 15."

题解

使用正则表达式和 Function 构造函数。

function interpolate(template, data) {
  return template.replace(/{{(.+?)}}/g, (match, exp) => {
    const func = new Function(...Object.keys(data), `return ${exp}`);
    return func(...Object.values(data));
  });
}

// 测试函数功能
const template =
  "The sum of {{ a }} and {{ b }} is {{ a + b }} and the product is {{ a * b }}.";
const data = { a: 5, b: 3 };

const result = interpolate(template, data);
console.log(result); // 输出: "The sum of 5 and 3 is 8 and the product is 15."

本页目录