Reputation: 1846
I have a string eg. Here is a (TEST)
, I need to convert it to Here is a \\(TEST)\\
I tried using str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
but it didn't work for me.
Upvotes: 1
Views: 100
Reputation: 776
This solves your problem:
var str = "Here is a (TEST)";
str = str.replace("(", "\\\\(");
str = str.replace(")", ")\\\\");
Upvotes: 2
Reputation: 473
<script>
var str = "(TEST)";
str = str.replace("(", "\\\\(").replace(")", ")\\\\");
alert(str);
</script>
Try something like this
Upvotes: 0
Reputation: 785196
Unless I'm missing something this can be done using:
'Here is a (TEST)'.replace(/([(){}\[\]])/g, '\\\\$1');
//=> "Here is a \\(TEST\\)"
Upvotes: 1