Skip to content

Instantly share code, notes, and snippets.

@hoIIer
Created August 9, 2021 17:43
Show Gist options
  • Save hoIIer/440f537e057768b93d038665482b1ae8 to your computer and use it in GitHub Desktop.
Save hoIIer/440f537e057768b93d038665482b1ae8 to your computer and use it in GitHub Desktop.
CSS.escape shim function that works in browser & node.
/**
* CSS escape shim that works in both node and the browser.
*
* see: https://github.com/mathiasbynens/CSS.escape/blob/master/css.escape.js
*/
export function escape(sel) {
const result = [];
for (const [index, letter] of Array.from(sel).entries()) {
const charCode = letter.charCodeAt(0);
if (charCode === 0x0000) {
result.push('\uFFFD');
continue;
}
if (
(charCode >= 0x0001 && charCode <= 0x001F)
|| charCode === 0x007F
|| (index === 0 && charCode >= 0x0030 && charCode <= 0x0039)
|| (
index === 1
&& charCode >= 0x0030
&& charCode <= 0x0039
&& sel.charCodeAt(0) === 0x002D
)
) {
result.push(`\\${charCode.toString(16)} `);
continue;
}
if (
charCode >= 0x0080
|| charCode === 0x002D
|| charCode === 0x005F
|| (charCode >= 0x0030 && charCode <= 0x0039)
|| (charCode >= 0x0041 && charCode <= 0x005A)
|| (charCode >= 0x0061 && charCode <= 0x007A)
) {
result.push(letter);
continue;
}
result.push(`\\${letter}`);
}
return result.join('');
}
export default {
escape,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment