Last active
August 7, 2025 18:22
-
-
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 NEEDS_ESCAPE = new RegExp("(^[0-9A-Za-z]|[,-=<>#&!%:;@~'`\"])|([\\^\\$\\\\\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|\\/])|([\\t\\f\\n\\v\\r\\x20])|(\\s(?<![\\u0000-\\u007f]))|([\\ud800-\\udbff](?=$|[^\\udc00-\\udfff])|[\\udc00-\\udfff](?<=^.|[^\\ud800-\\udbff].))", "gs"); | |
const CHAR_ESCAPES = { "\u0009": '\\t', "\u000c": '\\f', "\u000a": '\\n', "\u000b": '\\v', "\u000d": '\\r', "\u0020": '\\x20' }; | |
function _escape(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 CHAR_ESCAPES[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 function escape(s) { | |
if (typeof s !== 'string') | |
throw new TypeError("input argument must be a string") | |
return s.replaceAll(NEEDS_ESCAPE, _escape); | |
} | |
export default (RegExp.escape ?? escape).bind(RegExp); | |
//if (!("escape" in RegExp)) RegExp.escape = escape; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment