RegExp.escape()

AJ ONeal coolaj86 at gmail.com
Fri Jun 15 08:40:57 PDT 2012


YES. PLEASE put this in!

http://stackoverflow.com/a/6969486/151312

function escapeRegExp(str) {

  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

}

I'm doing my best to reply to every single question that pops up on
stackoverflow and point them to this answer... but there are just too many
wrong answers out there.

AJ ONeal

On Fri, Jun 15, 2012 at 9:17 AM, T.J. Crowder <tj at crowdersoftware.com>wrote:

> On 23 March 2012 12:12, Steven Levithan wrote:
> > Erik Corry wrote:
> > > In perl the recommended version is
> > >
> > > text.replace(/([^a-zA-Z0-9])/g, "\\$1")
> > >
> > > which is future-proof and safe and I think this also works for JS.
> >
> > It's probably future-proof and safe, but it escapes 65,520 characters
> more
> > than necessary.
> >
> > Anyway, no big deal if this isn't added. I have, however, seen a lot of
> > developers get this wrong when trying to do it themselves (e.g., the blog
> > post that started this thread was not safe until it was updated 4+ years
> > later, and it wasn't the worst I've seen).
>
> I've seen at least three that missed things out as well. The "all but
> alnums" approach doesn't seem to occur to people.
>
> On 23 March 2012 12:37, Steven Levithan wrote:
> > Erik Corry wrote:
> > > In perl the recommended version is
> > > text.replace(/([^a-zA-Z0-9])/g, "\\$1")
> >
> > For the record, most languages with modern regular expressions include a
> > built in method for this.
> >
> > For instance:
> >
> > * Perl: quotemeta(str)
> > * PHP: preg_quote(str)
> > * Python: re.escape(str)
> > * Ruby: Regexp.escape(str)
> > * Java: Pattern.quote(str)
> > * C#, VB.NET: Regex.Escape(str)
>
> Indeed. +1 for RegExp.escape in ES.
>
> -- T.J.
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120615/f67c0194/attachment-0001.html>


More information about the es-discuss mailing list