Replace all double quotes within String

Here's how

String details = "Hello \"world\"!";
details = details.replace("\"","\\\"");
System.out.println(details);               // Hello \"world\"!

Note that strings are immutable, thus it is not sufficient to simply do details.replace("\"","\\\""). You must reassign the variable details to the resulting string.


Using

details = details.replaceAll("\"","&quote;");

instead, results in

Hello &quote;world&quote;!

Would not that have to be:

.replaceAll("\"","\\\\\"")

FIVE backslashes in the replacement String.


To make it work in JSON, you need to escape a few more character than that.

myString.replace("\\", "\\\\")
    .replace("\"", "\\\"")
    .replace("\r", "\\r")
    .replace("\n", "\\n")

and if you want to be able to use json2.js to parse it then you also need to escape

   .replace("\u2028", "\\u2028")
   .replace("\u2029", "\\u2029")

which JSON allows inside quoted strings, but which JavaScript does not.


I think a regex is a little bit of an overkill in this situation. If you just want to remove all the quotes in your string I would use this code:

details = details.replace("\"", "");

Tags:

Java

Regex