malcoauri
malcoauri

Reputation: 12189

How to add slash to quotes in JS string?

There is the following example of string:

var s = "abcdwq'xx'x";

How can I screen ordinary quotes, i.e. add slash? I tried to use the following code:

s.replace('/(["\'\])/g', "\\$1")

but it doesn't work. Thanks in advance

Upvotes: 0

Views: 6819

Answers (1)

Barmar
Barmar

Reputation: 780818

Don't put the regular expression in quotes, that makes it an ordinary string.

var s = "abcdwq'xx'x";
console.log(s.replace(/(["'])/g, "\\$1"));

Also, you were escaping the ] that ends [.

If you just want to escape single quotes, you don't need the brackets or capture group. Just do:

var s = "abcdwq'xx'x";
console.log(s.replace(/'/g, "\\'"));

Upvotes: 12

Related Questions