Reputation: 6729
How can I escape the double quotes in a string? For eg,
input: "Nobody"
output: \"Nobody\"
I tried sth like this,which is not working:
String name = "Nobody";
name.replaceAll("\"", "\\\"");
Upvotes: 0
Views: 493
Reputation: 5839
adarshr is right but also, notice that you are ignoring the returned string, do it like this:
String name = "Nobody";
name = name.replaceAll("\"", "\\\"");
Strings in java are imutable
Edit: Since I wrote that, adarshr has changed his answer to the better (if anyone wonder why I wrote that)
Upvotes: 5
Reputation: 435
Take a look at http://www.bradino.com/javascript/string-replace/ as it gives tips on replacing all.
You can do just one with:
var name = '"Nobody"'; name = name.replace("\"", "\\"");
Regards
AJ
Upvotes: 0
Reputation: 2136
name.replaceAll(...) does not change name - it returns the string so you need to write:
name = name.replaceAll(...)
besides that your string doesn't contain a "
Upvotes: 0
Reputation: 62573
Because your string "Nobody" doesn't have any double quotes in it!
String name = "Nobo\"dy";
name = name.replaceAll("\"", "\\\\\"");
System.out.println(name);
Besides, you don't need a RegEx for such a simple replacement.
Just try
name = name.replace("\"", "\\\"");
Upvotes: 6