无法用包含 [ 和 ] 的字符串替换我的字符串

Unable to replace my string with string containing [ and ]

我无法从我的总字符串中 {info.inner.interest[0]} 字符串,即使我的总字符串包含要替换的字符串

我在 google 中搜索了相同的问题并尝试了其他代码,尽管这对我不起作用。请看下图

var a = "text :Array Item : {info.inner.interest[0]}",
  replaceThis = "info.inner.interest[0]",
  outPut = a.replace(new RegExp('{' + replaceThis + '}', 'g'), 'hello me!!')
console.log(outPut);

当我从 replaceThis 中删除 [0] 时,此代码有效。为什么当我使用 [..] 符号时此代码不起作用。请帮我。

许多字符在正则表达式中具有特殊含义。 []表示字符集.表示任意字符,不是文字点.如果要匹配包含任何特殊字符的字符串,则需要先将这些字符用反斜杠转义,例如:

const escape = str => str.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&');

var a = "text :Array Item : {info.inner.interest[0]}",
  replaceThis = "info.inner.interest[0]",
  outPut = a.replace(new RegExp('{' + escape(replaceThis) + '}', 'g'), 'hello me!!')
console.log(outPut);

这导致正则表达式为

{info\.inner\.interest\[0\]}

而不是

{info.inner.interest[0]}

您需要转义正则表达式中的特殊字符。 replaceThis = "info.inner.interest\[0\]"

或在shorthand下方

var a = "text :Array Item : {info.inner.interest[0]}",
  replaceThis = "info.inner.interest[0]",
  outPut = a.replace(/\[|\]/g, 'hello me!!');
console.log(outPut);

这是我的解决方案:

var a = "text :Array Item : {info.inner.interest[0]}";
replaceThis = "info.inner.interest[0]";
outPut = a.replace(replaceThis, 'hello me!!');
console.log(outPut);

您使用了错误的正则表达式。应该是(info\.inner\.interest\[0\])。请参阅以下代码:

var a = "text :Array Item : {info.inner.interest[0]}",
  replaceThis = "info.inner.interest[0]",
  outPut = a.replace(new RegExp('(info\.inner\.interest\[0\])', 'g'), 'hello me!!')
console.log(outPut);