Dennis Liger
Dennis Liger

Reputation: 1516

Javascript regex to replace quotes without front backslash

I'm looking for javascript regex to replace quotes without front backslash.

For example:

'"'.replace(xxx, yyy); -> '\"'
'\"'.replace(xxx, yyy); -> '\"'
'\\"'.replace(xxx, yyy); -> '\\\"'

Currently, I did the following, but I believe there is a better way.

content = content.replace(/"/g, '\\"');
content = content.replace(/\\\\"/g, '\\"');

Upvotes: 0

Views: 62

Answers (3)

MaxZoom
MaxZoom

Reputation: 7753

As I understand the question you would like to replace only those quotes that are not proceeded with the backslash character. For this you could use below regex

var str = 'this"quote but not \"this one';
console.log(str.replace(/(([^\\])(["]))/g, "$2\\$3"));

Upvotes: 1

000
000

Reputation: 27227

JSON.stringify('abc " def')

returns

"abc \" \" def"

Upvotes: 1

Ali Somay
Ali Somay

Reputation: 625

If you want to replace all the '"' with '\"',

then

var replacedString = 'string with " " quotes'.replace(/"/g,'\\\"');

should work.

Upvotes: 0

Related Questions