String replace Double quotes into curly brackets
Try using a global regex and use capture groups:
let str = '"This" is my "new" key "string"';
str = str.replace(/"([^"]*)"/g, '{$1}');
console.log(str);
The "([^"]*)"
regex captures a "
, followed by 0 or more things that aren't another "
, and a closing "
. The replacement uses $1
as a reference for the things that were wrapped in quotes.
Your code currently is only working for the first occurrence of each {
and }
. The easiest way to fix this would be to loop while there is still a "
in str
:
let str = '"This" is my "new" key "string"';
while (str.includes('"')) {
str = str.replace(/"/,'{').replace(/"/,'}');
}
console.log(str);