RegExp.escape()

C. Scott Ananian ecmascript at cscott.net
Sat Jun 13 06:06:46 UTC 2015


On Sat, Jun 13, 2015 at 1:51 AM, Mark S. Miller <erights at google.com> wrote:

> Nice! Inspired
>
>   // Based on
>   // https://github.com/benjamingr/RexExp.escape/blob/master/polyfill.js
>   function re(template, ...subs) {
>     const parts = [];
>     const numSubs = subs.length;
>     for (let i = 0; i < numSubs; i++) {
>       parts.push(template.raw[i]);
>       parts.push(subs[i].replace(/[\/\\^$*+?.()|[\]{}]/g, '\\$&'));
>     }
>     parts.push(template.raw[numSubs]);
>     return RegExp(parts.join(''));
>   }
>

A slight tweak allows you to pass flags:
```
function re(flags, ...args) {
  if (typeof template !== 'string') {
     // no flags given
     return re(undefined)(flags, ...args);
  }
  return function(template, ...subs) {
    const parts = [];
    const numSubs = subs.length;
    for (let i = 0; i < numSubs; i++) {
      parts.push(template.raw[i]);
      parts.push(subs[i].replace(/[\/\\^$*+?.()|[\]{}]/g, '\\$&'));
    }
    parts.push(template.raw[numSubs]);
    return RegExp(parts.join(''), flags);
  };
}
```

Use like this:
```
var r = re('i')`cAsEiNsEnSiTiVe`;
```
  --scott
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150613/264f2cce/attachment.html>


More information about the es-discuss mailing list