Search code examples
javascriptreplaceall

Unable to replace my string with string containing [ and ]


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.


Solution

  • 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]}