Escaping quotes in Java

Here is a simple tip to replace a quote with a backslash and a quote :
‘ ==> \’

public static String echappeApostrophe(String s) {
String temp;
temp = s.replaceAll(“‘”,”\\\\'”);
return temp;

I needed 4 backslashes

To better understand what is happening here, i printed out a few values :

String a = “\'”;
String b = “\\'”;
String c = “\\\'”;
String d = “\\\\'”;


output :


This is useful if for instance you need to pass, from a Java program, a string with a quote inside as a parameter to a dynamically generated
JavaScript function.

Else you get a Javascript error because the quote is not escaped.

More info here :