* Escapes a CSS string. * @param {string} css the string to escape. * @return {string} the escaped string. * @throws {TypeError} if the input value is not a string. * @throws {InvalidCharacterError} if the string contains an invalid character. * @see https://drafts.csswg.org/cssom/#serialize-an
(css)
| 65 | * @see https://drafts.csswg.org/cssom/#serialize-an-identifier |
| 66 | */ |
| 67 | function escapeCss(css) { |
| 68 | if (typeof css !== 'string') { |
| 69 | throw new TypeError('input must be a string') |
| 70 | } |
| 71 | let ret = '' |
| 72 | const n = css.length |
| 73 | for (let i = 0; i < n; i++) { |
| 74 | const c = css.charCodeAt(i) |
| 75 | if (c == 0x0) { |
| 76 | throw new InvalidCharacterError() |
| 77 | } |
| 78 | |
| 79 | if ( |
| 80 | (c >= 0x0001 && c <= 0x001f) || |
| 81 | c == 0x007f || |
| 82 | (i == 0 && c >= 0x0030 && c <= 0x0039) || |
| 83 | (i == 1 && c >= 0x0030 && c <= 0x0039 && css.charCodeAt(0) == 0x002d) |
| 84 | ) { |
| 85 | ret += '\\' + c.toString(16) + ' ' |
| 86 | continue |
| 87 | } |
| 88 | |
| 89 | if (i == 0 && c == 0x002d && n == 1) { |
| 90 | ret += '\\' + css.charAt(i) |
| 91 | continue |
| 92 | } |
| 93 | |
| 94 | if ( |
| 95 | c >= 0x0080 || |
| 96 | c == 0x002d || // - |
| 97 | c == 0x005f || // _ |
| 98 | (c >= 0x0030 && c <= 0x0039) || // [0-9] |
| 99 | (c >= 0x0041 && c <= 0x005a) || // [A-Z] |
| 100 | (c >= 0x0061 && c <= 0x007a) |
| 101 | ) { |
| 102 | // [a-z] |
| 103 | ret += css.charAt(i) |
| 104 | continue |
| 105 | } |
| 106 | |
| 107 | ret += '\\' + css.charAt(i) |
| 108 | } |
| 109 | return ret |
| 110 | } |
| 111 | |
| 112 | /** |
| 113 | * Describes a mechanism for locating an element on the page. |