7

How to replace all the Double quotes into both open and close curly brackets.

let str = "This" is my "new" key "string";

I tried with this regex

str.replace(/"/,'{').replace(/"/,'}')

But I end up with this:

{This} is my "new" key "string"

Here am getting only the first word is changing but i would like to change all the words. I want the result to be:

{This} is my {new} key {string}

Thanks in advance.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
YuvaMac
  • 419
  • 1
  • 6
  • 13
  • 1
    I kind of agree with whoever voted to reopen this question. While [the question about smart quotes](https://stackoverflow.com/questions/2202811/converting-straight-quotes-to-curly-quotes) is quite similar, someone looking for a simple way to replace symmetrical delimiters with balanced pairs would need to scroll quite far down to find [the only answer that doesn't assume the input is English prose text](https://stackoverflow.com/a/4300917) there. – Ilmari Karonen Dec 23 '18 at 20:14

4 Answers4

11

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.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
puddi
  • 811
  • 4
  • 10
4

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);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

Try like this

str.replace(/\"(.*?)\"/g, "{$1}")

we need to use g-gobal flag. Here capturing string between double quotes "", then replace with matched string curly braces

Raja Jaganathan
  • 33,099
  • 4
  • 30
  • 33
0

A very simple way to do that is to iterate over string as an array and every time it encounters character " replace it either by { or by } repeatedly.

let str = '"This" is my "new" key "string"';
let strArray = str.split("");
let open = true;
for (let i = 0; i < strArray.length; ++i) {
    if (strArray[i] == '"') {
        if (open === true) {
            strArray[i] = '{';
        }
        else {
           strArray[i] = '}';
        }
        open = (open == true) ? false : true;
    }
}
str = strArray.join("");
console.log(str)
BishalG
  • 1,414
  • 13
  • 24