javascript - 如何使用 RegEx 替换 JavaScript 中的 ${ variable } 字符串?
问题描述
假设我有以下字符串:
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 :-(
但由于某种原因,它不起作用。搜索字符串没有被替换。
怎么了?
Ps:这行得通!
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>
推荐阅读
- javascript - 数千次写入 MongoDB 后,NodeJS 崩溃
- python - 初学者问题 - 我只知道 python,我如何使用 API?
- python - 使用多个数据集训练神经网络 (Keras)
- python - Numba 数据类型错误:无法统一数组
- java - 有没有办法解密从特定表中散列成 CRC int 的字符串?
- python - Matplotlib 绘制比例三角形
- sql-server - 每个字符串的长度正好是 100 个字符
- javascript - 你如何打印出你输入的输入文本的值?Javascript 和 HTML
- python - 我如何使用 python 下载 youtube 视频
- c++11 - C++:使用 Youcompleteme 自动完成工具的 Vim 编辑器 - 不列出标准标题