Skip to content

Instantly share code, notes, and snippets.

@basselin
Last active October 29, 2020 23:43
Show Gist options
  • Save basselin/863c9f10e722b42feff6c382b15c6920 to your computer and use it in GitHub Desktop.
Save basselin/863c9f10e722b42feff6c382b15c6920 to your computer and use it in GitHub Desktop.
escapeSelector.js
// https://code.jquery.com/jquery-3.3.1.js
var escapeSelector = function(sel) { // $.escapeSelector()
var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g;
var fcssescape = function(ch, asCodePoint) {
if (asCodePoint) {
// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
if (ch === "\0") {
return "\uFFFD";
}
// Control characters and (dependent upon position) numbers get escaped as code points
return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " ";
}
// Other potentially-special ASCII characters get backslash-escaped
return "\\" + ch;
};
return (sel + '').replace(rcssescape, fcssescape);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment