Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match double quotes that doesn't have a preceding escape character

I have a string that has some double quotes escaped and some not escaped. Like this,

var a = "abcd\\\"\""
a = a.replace(/\[^\\\]\"/g, 'bcde')
console.log(a)

The string translates to literal, abcd\"". Now, i am using the above regex to replace non-escaped double quotes. And only the second double quote must be replaced.

The result must look like this,

abcd\"bcde

But it is returing the same original string, abcd\"" with no replacement.


2 Answers

You can use capture group here:

a = a.replace(/(^|[^\\])"/g, '$1bcde')
//=> abcd\"bcde
like image 170
anubhava Avatar answered Feb 02 '26 13:02

anubhava


A negative lookbehind is what you want. However it is not supported in the Regex' JS flavor.

You can achieve this by processing the result in two steps:

var a = "abcd\\\"\"";
console.log(a);
var result = a.replace(/(\\)?"/g, function($0,$1){ return $1?$0:'{REMOVED}';});
console.log(result);
like image 37
kbtz Avatar answered Feb 02 '26 13:02

kbtz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!