Escapes a value so it can be used as a CSS identifier, for example after # or .. The result is also safe inside a single-quoted attribute value such as [name='...'].
(String value)
| 34 | * [name='...']}. |
| 35 | */ |
| 36 | public static String escape(String value) { |
| 37 | String escaped = SPECIAL_CHARACTERS.matcher(value).replaceAll("\\\\$1"); |
| 38 | // CSS drops a backslash followed by a newline, so newlines need hex escapes instead. |
| 39 | escaped = escaped.replace("\\\n", "\\a ").replace("\\\r", "\\d ").replace("\\\f", "\\c "); |
| 40 | // CSS only requires the leading-digit escape for ASCII 0-9; non-ASCII Unicode digits |
| 41 | // (e.g. Arabic-Indic, fullwidth) are already valid identifier-start code points and must |
| 42 | // be left untouched, or they collide with the escape for a different ASCII digit. |
| 43 | char first = escaped.isEmpty() ? '\0' : escaped.charAt(0); |
| 44 | if (first >= '0' && first <= '9') { |
| 45 | escaped = |
| 46 | "\\" + (30 + Integer.parseInt(escaped.substring(0, 1))) + " " + escaped.substring(1); |
| 47 | } |
| 48 | return escaped; |
| 49 | } |
| 50 | } |