Last active
July 10, 2025 20:36
-
-
Save James-E-A/eca34e374196ea5e9b7100101391ce5d to your computer and use it in GitHub Desktop.
Javascript RegExp.escape ponyfill
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/escape#return_value | |
const R = /(^[0-9a\-zA-Z]|[,-=<>#&!%:;@~'`"])|([\^\$\\\.\*\+\?\(\)\[\]\{\}\|\/])|([\t\f\n\v\r\x20])|((?![\u0000-\u007f])\s)|([\ud800-\udbff](?=$|[^\udc00-\udfff])|(?<=^|[^\ud800-\udbff])[\udc00-\udfff])/g; | |
const W = { "\u0009": '\\t', "\u000c": '\\f', "\u000a": '\\n', "\u000b": '\\v', "\u000d": '\\r', "\u0020": '\\x20' }; | |
export function escape(s) { | |
if (typeof s !== 'string') | |
throw new TypeError("input argument must be a string") | |
return s.replaceAll( | |
R, | |
(m, hex, backslash, ascii_whitespace, nonascii_whitespace, lone_surrogate) => { | |
if (hex !== undefined) | |
return `\\x${hex.charCodeAt(0).toString(16).padStart(2, "0")}`; | |
if (backslash !== undefined) | |
return `\\${backslash}`; | |
if (ascii_whitespace !== undefined) | |
return W[ascii_whitespace]; | |
if (nonascii_whitespace !== undefined) | |
return `\\u${nonascii_whitespace.charCodeAt(0).toString(16).padStart(4, "0")}`; | |
if (lone_surrogate !== undefined) | |
return `\\u${lone_surrogate.charCodeAt(0).toString(16).padStart(4, "0")}`; | |
return m; | |
} | |
); | |
} | |
export default (RegExp.escape ?? escape); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment