Lightweight polyfill and ponyfill for the upcoming escape()
static method of RegExp
(proposal currently at Stage 3).
Currently passes all test262 tests except for cross-realm.js
, which I'm ignoring for now.
import { regExpEscape } from '@li/regexp-escape-polyfill'
const str = 'Hello, 🌍!$^.'
regExpEscape(str) // "\\x48ello\\x2c\\x20🌍\\x21\\$\\^\\."
new RegExp(regExpEscape(str)).test(str) // true
import '@li/regexp-escape-polyfill/global'
const str = 'Hello, 🌍!$^.'
RegExp.escape(str) // "\\x48ello\\x2c\\x20🌍\\x21\\$\\^\\."
new RegExp(RegExp.escape(str)).test(str) // true
import '@li/regexp-escape-polyfill/global'
import type { regExpEscape } from '@li/regexp-escape-polyfill/global'
declare global {
interface RegExpConstructor {
escape: typeof regExpEscape
}
}
RegExp.escape("ok") // passes type checking
Deno/1.46.0 x86_64-unknown-linux-gnu
Intel(R) Core(TM) i7-1065G7 CPU @ 1.30GHz
Name | Time (avg) | Iter/s | Bundle size (minified + gzipped) | Details |
---|---|---|---|---|
lionel-rowe/regexp-escape-polyfill | 1.222 µs | 817,741.3 | 498 B | Modern JS/ESM only, with TS support; aims for full compatibility with the spec (verified via test262) but may differ on implementation details. |
es-shims/RegExp.escape | 10.808 µs | 92,524.1 | 7.1 kB | Aims for ES3 compliance; written with CJS modules; more closely follows the implementation details of the algorithm in the spec. |
zloirock/core-js | 1.506 µs | 663,652.8 | 5.29 kB | CoreJS implementation; ES5 (?) support including various other polyfills; written with CJS modules |
denoland/std | 574 ns | 1,741,322.9 | 279 B | Written before the proposal reached Stage 3; written in TS/ESM; doesn't aim for spec compliance, but fulfills the same function. |