L P
L P

Reputation: 1846

How to append and prepend double escape to a string in JavaScript?

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

Answers (3)

EasyPush
EasyPush

Reputation: 776

This solves your problem:

var str = "Here is a (TEST)";
str = str.replace("(", "\\\\(");
str = str.replace(")", ")\\\\");

Upvotes: 2

Naveenkumar
Naveenkumar

Reputation: 473

<script>
var str = "(TEST)";
str = str.replace("(", "\\\\(").replace(")", ")\\\\");
alert(str);
</script>

Try something like this

Upvotes: 0

anubhava
anubhava

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

Related Questions