Coffee Space


Listen:

String Escape

Preview Image

Preview Image

TL;DR

Java doesn't have any native method for escaping a String and after investigating existing methods, I decided to write my own. I posted the solution to Stack Overflow.

Problem

I was writing some JSON to a file, but the Strings themselves contained escape characters (or theoretically could), i.e.:

{
  "key" : ""value""
}

Ideally you would want to escape the speech marks (") if you wanted the structure to be parsed correctly by JSON, i.e.:

{
  "key" : "\"value\""
}

But actually this problem occurs in other places too, this isn't even the first time I had to solve something similar. When parsing comments for example to be displayed in HTML, you don't want users injecting <script> tags for example that may run malicious JavaScript on the machines of other users. (P.S. Any HTML parsed should be considered harmful, it's a lot safer to filter out all HTML and add it back in later than to try and only allow select HTML through.)

Existing

Many of the solutions suggest adding the Apache Commons Text and using StringEscapeUtils. Some of the other solutions were simply wrong.

Solution

The solution I created:

/**
 * escape()
 *
 * Escape a give String to make it safe to be printed or stored.
 *
 * @param s The input String.
 * @return The output String.
 **/
public static String escape(String s){
  return s.replace("\\", "\\\\")
          .replace("\t", "\\t")
          .replace("\b", "\\b")
          .replace("\n", "\\n")
          .replace("\r", "\\r")
          .replace("\f", "\\f")
          .replace("\'", "\\'")
          .replace("\"", "\\\"");
}

The escape list is from Oracle's list. (Note that \\ is escaped first as you don't want to re-escape it later.)

This solution isn't as fast as it could be, but it should work. Ideally you would only parse the String once and you wouldn't need to keep rebuilding your String array. For small Strings this should be fine. This solution was more than fine for me as the Strings I escaped were less than 64 characters, theoretically a maximum of 836 even in the worst case scenario. If escaping larger Strings, you can do much better.

If you're thinking about this from the perspective of storing data, also consider something like converting it to Base64 representation - it's fast, single parse and uses not too much extra space.