RegExp.escape()

C. Scott Ananian ecmascript at cscott.net
Tue Jun 30 14:54:48 UTC 2015


On Tue, Jun 30, 2015 at 3:46 AM, Benjamin Gruenbaum <benjamingr at gmail.com>
wrote:

> I'm still not sure if it's worth it, after all it's just sugar for
> `RegExp.escape(str).replace(/[a-z]/gu, m => `\\${m}`)`
>

I think you're making my point!  And I hope your version of `RegExp.escape`
doesn't use hexadecimal or unicode escapes.  (And that no one extends it to
do so in the future.)

Over at
https://github.com/benjamingr/RegExp.escape/issues/29#issuecomment-116845364
I also suggested that you consider:
```
RegExp.escape(str, /[0-9]$/)
```
versus:
```
RegExp.escape(str).replace(/[0-9]$/, /* what goes here? */);
```
and then what happens with the latter code if `str` is `"\\010"` (ie, using
a literal backlash) or `$` (since `RegExp.escape('$') == "\\024"`).

It would also be nice to be able to do:
```
str.replace(/something/, (c) => RegExp.escape(c, /[^]/g));
```
that is, to be able to easily get a version of `RegExp.escape` that safely
encodes *every* character it is given.

Let's give programmers powerful tools that aren't footguns, instead of
making them play with `String#replace` after the fact and risk losing toes
on the corner cases.
  --scott
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150630/8a01ac78/attachment.html>


More information about the es-discuss mailing list