Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace Double quotes into curly brackets [duplicate]

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.

like image 597
YuvaMac Avatar asked Dec 23 '18 06:12

YuvaMac


People also ask

How do you replace a double quote in a string?

If you want to add double quotes(") to String, then you can use String's replace() method to replace double quote(") with double quote preceded by backslash(\").

How do you replace double quotes with empty strings in Java?

You can use String#replace() for this. String replaced = original. replace("\"", " "); Note that you can also use an empty string "" instead to replace with.

How do I replace double quotes in Excel VBA?

chr(34) is the character code for a double quote. You could also use replace(mystring, """", "") that """" gets evaluated as one double-quote character, but I believe the chr(34) is much less confusing. replace(mystring, chr(34), "") does not work for me with cscript on Windows 2012 R2.

How do you encode double quotes?

When using double quotes "" to create a string literal, the double quote character needs to be escaped using a backslash: \" .


1 Answers

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.

like image 81
puddi Avatar answered Nov 15 '22 01:11

puddi