Thursday, September 18, 2008

Back slashes needed to escape a quote in Java

During today's work, I faced the problem of escaping the quote, double quote and line break inside a String while sending it into javascript.

The following code was the approach first came into my mind:

String eStr = orginalStr.replaceAll("\"", "\\\"");
eStr = eStr.replaceAll("'", "\\'");
eStr = eStr.replaceAll("\\r\\n", "<br>");

Ironically, none single line of these code works. After some research, I figured out the correct way should be:

String eStr = orginalStr.replaceAll("\"", "\\\\\"");
eStr = eStr.replaceAll("'", "\\\\'");
eStr = eStr.replaceAll("\r\n", "<br>");

It seems my previous code replace a quote by quote itself. The interesting result is the following two lines are quite the same:

String eStr = orginalStr.replaceAll("\"", "\\\"");
String eStr = orginalStr.replaceAll("\"", "\"");

So four more back slashes are required to escape the quote or single quote. However six back slashes are needed to escape back slash itself.

No comments: