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