Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string containing " with \"?

Tags:

java

string

How can I replace string containing " with \" ?

replace(""","\"") is not working for me.

public static String replaceSpecialCharsForJson(String str){
    return str.replace("'","\'")
              .replace(":","\\:")
              .replace("\"","\"")
              .replace("\r", "\\r")
              .replace("\n", "\\n");
} 
like image 288
Yogesh Avatar asked Apr 29 '26 16:04

Yogesh


1 Answers

You can try with:

replace("\"","\\\"")

Since both " and \ are metacharacters, you have to escape them with \

like image 165
Konstantin Yovkov Avatar answered May 01 '26 05:05

Konstantin Yovkov