RegExp. quoteText()

Andrea Giammarchi andrea.giammarchi at gmail.com
Wed Aug 28 14:57:33 PDT 2013


quick one: the hyphen has meaning only inside squared brackets and between
ranges ... this has no meaning `[_-]` so doesn't this `[a-]`



On Wed, Aug 28, 2013 at 9:23 AM, Claude Pache <claude.pache at gmail.com>wrote:

>
> Le 28 août 2013 à 17:23, Axel Rauschmayer <axel at rauschma.de> a écrit :
>
> This must have been suggested before, but it would be great to have a
> built-in function for quoting text in a RegExp.
>
> For example:
>
> ```js
> RegExp.quoteText = function (text) {
>     return text.replace(/[\^\$\\.*+?()[\]{}|]/g, '\\\$&');
> };
>
> ```
>
> If you wanted to be extra thorough, you could include parens, braces and
> brackets.
>
>
>
> The complete list of characters that should be escaped is:
> ```
> . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
> ```
> (taken from [1]). Importantly, characters that have special meaning only
> in some context should also be included. For example, consider the hyphen
> `-`, which has special meaning only inside `[...]`: People may want to
> write:
> ```
> var charList = 'abcd123-_';
> var re = new RegExp( '[' + RegExp.quote(charList) + ']' )
> ```
> in order to construct a regexp that matches any character of `charList`.
>
> --Claude
>
> [1] http://php.net/manual/en/function.preg-quote.php
>
>
> --
> Dr. Axel Rauschmayer
> axel at rauschma.de
>
> home: rauschma.de
> twitter: twitter.com/rauschma
> blog: 2ality.com
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
>
> _______________________________________________
> 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/20130828/0602ea6e/attachment-0001.html>


More information about the es-discuss mailing list