From 0d2f45fe3198f29170ddda9d6d42175c3c70fb7e Mon Sep 17 00:00:00 2001 From: "Rodney, Tiara" Date: Thu, 1 May 2025 19:25:37 +0200 Subject: [PATCH] feat: add polyfill for RegExp.escape the method is currently in ECMAScript standard draft 4 and not yet adopted broadly enough. V8 has basic support, but I'm not betting on it coming soon, so I've implemented a simple polyfill. --- src/polyfill/regexp.ts | 11 +++++++++++ src/types/regexp.d.ts | 8 ++++++++ tsconfig.json | 3 ++- 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 src/polyfill/regexp.ts create mode 100644 src/types/regexp.d.ts diff --git a/src/polyfill/regexp.ts b/src/polyfill/regexp.ts new file mode 100644 index 0000000..ca50ad4 --- /dev/null +++ b/src/polyfill/regexp.ts @@ -0,0 +1,11 @@ +/** + * Polyfill for `RegExp.escape`, ensuring compatibility with environments + * that do not yet support this method. + * + * @see src/types/regexp.d.ts For the TypeScript type declaration. + */ +if (!RegExp.escape) { + RegExp.escape = function (str: string): string { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + }; +} diff --git a/src/types/regexp.d.ts b/src/types/regexp.d.ts new file mode 100644 index 0000000..4274c95 --- /dev/null +++ b/src/types/regexp.d.ts @@ -0,0 +1,8 @@ +interface RegExpConstructor { + /** + * @see + * {@link https://tc39.es/proposal-regex-escaping/#sec-regexp.escape + * | ECMAScript Stage 4 Draft} + */ + escape?(str: string): string; +} diff --git a/tsconfig.json b/tsconfig.json index 700b8f0..e3c3f14 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,6 +15,7 @@ "lib": ["esnext.weakref", "dom"] }, "include": [ - "src/**/*.ts" + "src/**/*.ts", + "src/types/**/*.d.ts" ] }