简体   繁体   English

如何使用RegEx替换JavaScript中的$ {variable}字符串?

[英]How to replace ${ variable } strings in JavaScript using RegEx?

Let's say I have the following string: 假设我有以下字符串:

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

I want to replace ${ title } with any other string. 我想用任何其他字符串替换${ title } The placeholder can also look like this: 占位符也可以如下所示:

  • ${title}
  • ${ title}
  • ${title }

So, I created a replace function using a regex: 因此,我使用正则表达式创建了一个替换函数:

// 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);
}

I call it like this: 我这样称呼它:

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

But for some reason it doesn't work. 但是由于某种原因,它不起作用。 The searchstring is not being replaced. 搜索字符串不会被替换。

What's wrong? 怎么了?

Ps: This works! 附:这行得通!

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

Dang it, while writing the question I figured out, that I need to add 3(!) backslashes to escape the $ sign like this: 当我写出我想出的问题时,我需要添加3(!)反斜杠来逃避$符号,就像这样:

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

So, the correct function looks like this: 因此,正确的函数如下所示:

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

Calling it like this: 像这样调用它:

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

Returns: 返回值:

<title>TOAST!!</title>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM