Le 28 août 2013 à 17:23, Axel Rauschmayer <[email protected]> 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
> [email protected]
>
> home: rauschma.de
> twitter: twitter.com/rauschma
> blog: 2ality.com
>
> _______________________________________________
> es-discuss mailing list
> [email protected]
> https://mail.mozilla.org/listinfo/es-discuss
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss