How can I escape the double quotes in a string? For eg,
input: "Nobody"开发者_Python百科
output: \"Nobody\"
I tried sth like this,which is not working:
String name = "Nobody";
name.replaceAll("\"", "\\\"");
Because your string "Nobody" doesn't have any double quotes in it!
String name = "Nobo\"dy";
name = name.replaceAll("\"", "\\\\\"");
System.out.println(name);
- Your string didn't have double quotes
- You weren't reassigning name (remember that strings are immutable in Java)
- Your regex wasn't exactly correct.
Besides, you don't need a RegEx for such a simple replacement.
Just try
name = name.replace("\"", "\\\"");
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)
name.replaceAll(...) does not change name - it returns the string so you need to write:
name = name.replaceAll(...)
JavaDoc
besides that your string doesn't contain a "
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
精彩评论