簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM