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.
This commit is contained in:
Rodney, Tiara 2025-05-01 19:25:37 +02:00
parent 74465875cb
commit 0d2f45fe31
No known key found for this signature in database
GPG key ID: 5CD8EC1D46106723
3 changed files with 21 additions and 1 deletions

11
src/polyfill/regexp.ts Normal file
View file

@ -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, '\\$&');
};
}

8
src/types/regexp.d.ts vendored Normal file
View file

@ -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;
}

View file

@ -15,6 +15,7 @@
"lib": ["esnext.weakref", "dom"]
},
"include": [
"src/**/*.ts"
"src/**/*.ts",
"src/types/**/*.d.ts"
]
}