Home > OS >  How to replace inner double quotes to single quote using regex
How to replace inner double quotes to single quote using regex

Time:11-26

I've got something like this data that comes from API and I need to do JSON.parse this, but the problem was there were inner double quotes so I can't parse it what should I do, can I use regex or something.

const dataString = '{"EN" : "2. This English "Blha Blha"  "Woo Woo" something wrong."}';

I also used this regex

replace(/(^"|"$)|"/g, "'");

but by using this regex it's replace all the double quotes with single quotes like this =>

{'EN' : '2. This English 'Blha Blha'  'Woo Woo' something wrong.'};

I only want to replace the quotes like this

{'EN' : '2. This English "Blha Blha"  "Woo Woo" something wrong.'};

CodePudding user response:

The thing is that single quotes are not valid symbols for JSON if they are used to wrap key/values. To make it clear - you need to escape double-quote symbols in values. A better approach is to update your API with that correction. More ugly but working way is placed below:

const dataString = '{"EN" : "2. This English "Blha Blha"  "Woo Woo" something wrong."}';
const normalize = (dataString) => {
  let newString = dataString;
  newString = newString.replaceAll(`"`, `\\\"`);
  newString = newString.replaceAll(`{\\\"`, `{"`);
  newString = newString.replaceAll(`\\\"}`, `"}`);
  newString = newString.replaceAll(`\\\" : \\\"`, `" : "`);
  return newString;
};
console.log(JSON.parse(normalize(dataString)));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related