EncodersImpl implements Encoders { public String js(String s) { if (s == null) { return null; } final int l = s.length(); final StringBuffer sb = new StringBuffer(l); for (int i = 0; i < l; i++) { final char ch = s.charAt(i); switch (ch) { case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; case '/': sb.append("\\/"); break; case '\\': sb.append("\\\\"); break; case '\"': sb.append("\\x22"); break; case '&': sb.append("\\x26"); break; case '\'': sb.append("\\x27"); break; default: if (ch >= '\u0000' && ch <= '\u001F') { sb.append("\\x").append(ch <= '\u000F' ? "0" : "").append(Integer.toHexString((int) ch)); } else { sb.append(ch); } } } return sb.toString(); }  String js(String s); String html(String s);  }
@Test public void testEncoderJs() { assertEquals("\\b \\t \\n \\f \\r", encoders.js("\b \t \n \f \r")); assertEquals("\\/ \\\\ \\x22 \\x26 \\x27", encoders.js("/ \\ \" & '")); assertEquals("\\x00 \\x0f \\x10 \\x1f", encoders.js("\u0000 \u000f \u0010 \u001f")); assertEquals("\\tfunction() { return \\x27Hello World\\x27; }", encoders.js("\tfunction() { return 'Hello World'; }")); assertNull(encoders.js(null)); }