EscapeUtils { public static String escapeJSString(String s) { Matcher matcher = JSSTR_RE.matcher(s); if (!matcher.find()) return s; StringBuilder result = new StringBuilder(); int beginIndex = 0; do { int endIndex = matcher.start(); if (beginIndex < endIndex) result.append(s.substring(beginIndex, endIndex)); char c = matcher.group().charAt(0); result.append('\\'); switch (c) { case '\b': result.append('b'); break; case '\t': result.append('t'); break; case '\n': result.append('n'); break; case 0x000b: result.append('v'); break; case '\f': result.append('f'); break; case '\r': result.append('r'); break; case '"': case '\'': case '\\': result.append(c); break; default: result.append(String.format("u%04x", (int) c)); break; } beginIndex = matcher.end(); } while (matcher.find(beginIndex)); if (beginIndex < s.length()) result.append(s.substring(beginIndex)); return result.toString(); } private  EscapeUtils(); static String escapeHtml(String s, boolean newline); static String encodeUri(String s); static String escapeJSString(String s); static final Pattern HTML_RE; static final Map<String, String> HTML_ESC_MAP; }
@Test public void testEscapeJSString() { String expected = "\\u0000\\b\\t\\n\\v\\f\\r\\\"\\'\\\\\\u2028\\u2029"; String actual = EscapeUtils.escapeJSString("\u0000\b\t\n\u000b\f\r\"\'\\\u2028\u2029"); System.out.println("* JSString\n exp: [" + expected + "]\n act: [" + actual + "]"); assertThat(actual, equalTo(expected)); }