首页 > 解决方案 > 如何使用 RegEx 替换 JavaScript 中的 ${ variable } 字符串?

问题描述

假设我有以下字符串:

const str = '<title>${ title }</title>';

我想${ title }用任何其他字符串替换。占位符也可以如下所示:

所以,我使用正则表达式创建了一个替换函数:

// If name = "title", then this function should replace ${ title } within str with content.
function replace(str, name, content) {
  const pattern = `\${[ ]{0,}${name}[ ]{0,}}`;
  const rex = new RegExp(pattern, 'g');
  console.log(rex); // Outputs /${[ ]{0,}title[ ]{0,}}/g
  return str.replace(rex, content);
}

我这样称呼它:

const str = '<title>${ title }</title>';
const title = 'TOAST!!';
const res = replace(str, 'title', title); // ${ title } is not replaced :-(

但由于某种原因,它不起作用。搜索字符串没有被替换。

怎么了?

Ps:这行得通!

str.replace(/\${[ ]{0,}title[ ]{0,}}/g, 'TOAST!!');

标签: javascriptregextemplates

解决方案


该死的,在写我想出的问题时,我需要添加 3(!) 反斜杠来转义 $ 符号,如下所示:

const pattern = `\\\${[ ]{0,}${name}[ ]{0,}}`;

因此,正确的函数如下所示:

function replace(str, name, content) {
  const pattern = `\\\${[ ]{0,}${name}[ ]{0,}}`;
  const rex = new RegExp(pattern, 'g');
  return str.replace(rex, content);
}

像这样称呼它:

const str = '<title>${ title }</title>';
const title = 'TOAST!!';
const res = replace(str, 'title', title);
console.log(res);

回报:

<title>TOAST!!</title>

推荐阅读