Arjun
Arjun

Reputation: 6729

java:replacing " with \"

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

Answers (4)

Fredrik
Fredrik

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

AnthonyJ
AnthonyJ

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

Gambrinus
Gambrinus

Reputation: 2136

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 "

Upvotes: 0

adarshr
adarshr

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);
  1. Your string didn't have double quotes
  2. You weren't reassigning name (remember that strings are immutable in Java)
  3. Your regex wasn't exactly correct.

Besides, you don't need a RegEx for such a simple replacement.

Just try

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

Upvotes: 6

Related Questions