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

发布时间 2023-10-24 18:23:25作者: 居无常

【转】https://blog.csdn.net/xiangzaixiansheng/article/details/132501772

要在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.