RegExp. quoteText()

Claude Pache claude.pache at gmail.com
Wed Aug 28 09:23:41 PDT 2013


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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130828/2a017520/attachment-0001.html>


More information about the es-discuss mailing list