[英]How to replace ${ variable } strings in JavaScript using RegEx?
假设我有以下字符串:
const str = '<title>${ title }</title>';
我想用任何其他字符串替换${ 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 :-(
但是由于某种原因,它不起作用。 搜索字符串不会被替换。
怎么了?
附:这行得通!
str.replace(/\${[ ]{0,}title[ ]{0,}}/g, 'TOAST!!');
当我写出我想出的问题时,我需要添加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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.