Unable to replace my string with string containing [ and ]

Viewed 68

I am unable to {info.inner.interest[0]} string from my total string even though my total string contain string to be replaced

I searched same question in google and tried others code even though that didn't work for me. Please have a look at image below

Error Image

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

This code is working when I remove [0] from replaceThis . Why this code is not working when I use [..] symbol. Please help me.

4 Answers

Many characters have a special meaning in a regular expression. [ and ] indicate a character set, and . indicates any character, not a literal dot. If you want to match a string containing any special characters, you need to escape those characters with backslashes first, for example:

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

This results in the regular expression being

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

rather than

{info.inner.interest[0]}

This is my solution:

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

You are using the wrong regex. It should be (info\\.inner\\.interest\\[0\\]). See below code :

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

You need to escape special characters in regex. replaceThis = "info.inner.interest\[0\]"

Or in shorthand below

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

Related