I am looking to replace quotes "" with single quotes '' within a string.
string = `bike "car" bus "'airplane'" "bike" "'train'"`
If a word is inside double quotes, it should be replaced with single quotes ('car' -> 'car')
If there are brackets inside single and double quotes -> the outer brackets should be removed (' 'airplane' ' -> 'airplane')
Therefore, the final result should be
`bike 'car' bus 'airplane' 'bike' 'train'`
I came across a similar regex
/(?=(?:"[^"]*?"[^"]*)+$)"([^"']*?)"/gm
but it does not meet my requirements completely, especially for the second condition
const regex = /(?=(?:"[^"]*?"[^"]*)+$)"([^"']*?)"/gm;
const str = `bike "car" bus "'airplane'" "bike" "'train'"`;
const subst = `'$1'`;
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
// bike 'car' bus "'airplane'" 'bike' "'train'"
I could achieve this by adding two more replacements, but I believe it can be done in a better way. Here is my solution
const result = str.replace(regex, subst).replace(/"'/g, "'").replace(/'"/g, "'"); //identify if the string contains " ' and replace it with ', and vice versa for ' " -> '