nodejs替换模版中${}的内容

要在js中想要替换替换模板中的${},可以使用字符串的replace()方法结合正则表达式或者函数来实现替换操作。

以下是两种常见的替换方式: 使用正则表达式:

方法一:

const template = "Hello, ${name}! Today is ${day}.";
const data = {
  name: "John",
  day: "Monday"
};

const result = template.replace(/\${(.*?)}/g, (match, key) => data[key]);
console.log(result);  // 输出: Hello, John! Today is Monday.

方法二:

const template = "Hello, ${name}! Today is ${day}.";
const data = {
  name: "John",
  day: "Monday"
};

const result = template.replace(/\${(.*?)}/g, (match, key) => {
  return data.hasOwnProperty(key) ? data[key] : match;
});
console.log(result);  // 输出: Hello, John! Today is Monday.

你可能感兴趣的:(前端,javascript,vue.js,node.js)