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

时间:2015-09-14 15:43:57

标签: javascript regex

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 个答案:

答案 0 :(得分:4)

You can use capture group here:

a = a.replace(/(^|[^\\])"/g, '$1bcde')
//=> abcd\"bcde

答案 1 :(得分:3)

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);