String replace Double quotes into curly brackets

  • A+
Category:Languages

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.

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: