CSSUtils { public static String escapeSelector(String css) { if (!css.contains(" ") && css.startsWith("#")) { return "#" + escapeIdentifier(css.substring(1, css.length())); } else { StringBuilder result = new StringBuilder(); String[] pieces = css.split(" "); for (String p : pieces) { if (p.startsWith("#")) { result.append("#").append(escapeIdentifier(p.substring(1, p.length()))).append(" "); } else { result.append(p).append(" "); } } return result.toString().trim(); } } private  CSSUtils(); static String escapeSelector(String css);  }
@Test public void shouldLeaveUncriticalSelectorsUntouched() { final String s1 = ".some-class"; Assert.assertEquals(".some-class", CSSUtils.escapeSelector(s1)); final String s2 = "body"; Assert.assertEquals("body", CSSUtils.escapeSelector(s2)); final String s3 = "body > div > ul:nth-child(3)"; Assert.assertEquals("body > div > ul:nth-child(3)", CSSUtils.escapeSelector(s3)); final String s4 = "#some-element"; Assert.assertEquals("#some-element", CSSUtils.escapeSelector(s4)); }
@Test public void shouldEscapeIdsWithSpecialCharacters() { final String[] specialChars = {"!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", ".", "/", ":", ";", "<", "=", ">", "?", "@", "[", "\\", "]", "^", "`", "{", "|", "}", "~"}; for (int i = 0; i < specialChars.length; i++) { final String s1 = "#some" + specialChars[i] + "el"; Assert.assertEquals("#some\\" + specialChars[i] + "el", CSSUtils.escapeSelector(s1)); final String s2 = "body > #some" + specialChars[i] + "el"; Assert.assertEquals("body > #some\\" + specialChars[i] + "el", CSSUtils.escapeSelector(s2)); } }