Brian
Brian

Reputation: 23

How can I replace two double quotes with one double quotes using Regex without capturing occurrences of one double quote?

I'm trying to do a replace on a JSON string. Something like this:

'{"val1":"1","val2":"2"","val3":"","val4":""}'

Looking at the value tied to key "val2", I'm getting two double quotes together " 2 " ", but I can't fix that because that's how I get the JSON, I'm trying to replace those occurrences with 1 double quote: from "2"" to "2"

I'm doing replace() but I can't find the right regex to do it. I have tried this:

replace(/""/g, '"')

If I do this it will replace "val3" and "val4" too.

This one doesn't work:

replace(/[^:]+"";/g, '"')

I'm trying to accomplish replace(REGEX_HERE): From "SomeCharactersHere"" to "SomeCharactersHere"

Upvotes: 2

Views: 1352

Answers (3)

Forty3
Forty3

Reputation: 2229

Have you tried:

var s = '{"val1":"1","val2":"2"","val3":"","val4":""}';
s = s.replace(/([^:])\"\"/g, '$1\"')
console.log(s);

This matches some non-colon character followed by a set of double-double-quotes and replaces it with the originally found non-colon character along with a single-double-quotes.

Per a suggestion by ctwheels:

var s = '{"val1":"1","val2":"2"","val3":"","val4":""}';
s = s.replace(/([^:]")"+/g, '$1')
console.log(s);

As mentioned, it will capture the possibility of more than one extraneous double-quote and simplifies the replacement to just $1. Thanks!

Upvotes: 1

JP Belanger
JP Belanger

Reputation: 119

I would add the comma in the match part.

'{"val1":"1","val2":"2"","val3":"","val4":""}'.replace(/"",/g, '\",');

I would also try to figure out why I'm getting badly formatted json :-)

Better yet:

'{"val1":"1","val2":"2"","val3":"","val4":""}'.replace(/"\([^"]+\)""/g, '"\1"')

Upvotes: 0

samanime
samanime

Reputation: 26537

Something like this should work.

const str = '{"val1":"1","val2":"2"","val3":"","val4":""}';
const cleaned = str.replace(/(\"+([^",]*)\"+)/g, (match,quotes,val) => `"${val}"`);
console.log(cleaned);
console.log(JSON.parse(cleaned));

Basically, it'll match each block of quotes (including extra quotes), then rewrite it to have only one pair of quotes.

Do note: it won't work if your values have commas. That's a limitation to this particular approach. If you need commas in the value, you could use this alternate regex:

/(\"([^"]*)\"+)/g

That one will work for commas, but won't work if you have a double-quote at the start of the string. You'd have to move the + in that case to the first one instead.

Upvotes: 0

Related Questions