-2
function replaceAll(str, find, replace) {
     return str.replace(new RegExp(find, 'g'), replace);
}
var data = ':['
data = replaceAll(data, ':\[', "/\\");

Error returned: Invalid regular expression: /:[/: Unterminated character class

I have seen other posts relating to this to escape the '[', but I have done that and it doesn't work.

Obviously I'm doing something wrong here and I'm not that familiar with RegEx things, so anybody help please?

2 Answers2

4

You would need to double escape as \ is an escape in a Javascript literal too:

data = replaceAll(data, ':\\[', "/\\");
Lloyd
  • 28,624
  • 4
  • 82
  • 95
2

Change your input like below,

data = replaceAll(data, ':\\[', "/\\");

You need to escape the backslash one more time when putting it inside RegExp constructor.

Avinash Raj
  • 166,785
  • 24
  • 204
  • 249