All you need to do is put \ before [ and ] to treat it as a regular character. This way your regex would become \[openshops\]
.
If you have multiple things that need to be replaced (eg. [shops]
and [state]
) you can do the following which dynamically creates the regex. This way you don't have to hard code it for each thing.
var str = "I went to the [shops], but the [shops] were [state]. I hate it when the [shops] are [state].";
var things = {
shops: "markets",
state: "closed"
};
for (thing in things) {
var re = new RegExp("\\["+thing+"\\]", "g");
str = str.replace(re, things[thing]);
}
console.log(str);
Note that you need to use two backslashes instead of just one when doing it this way.