RegExp.escape()

Mark S. Miller erights at google.com
Sat Jun 13 06:30:39 UTC 2015


Perfection?

  function re(first, ...args) {
    let flags = first;
    function tag(template, ...subs) {
      const parts = [];
      const numSubs = subs.length;
      for (let i = 0; i < numSubs; i++) {
        parts.push(template.raw[i]);
        const subst = subs[i] instanceof RegExp ? subs[i].source :
            subs[i].replace(/[\/\\^$*+?.()|[\]{}]/g, '\\$&');
        parts.push(subst);
      }
      parts.push(template.raw[numSubs]);
      return RegExp(parts.join(''), flags);
    }
    if (typeof first === 'string') {
      return tag;
    } else {
      flags = void 0;  // Should this be '' ?
      return tag(first, ...args);
    }
  }
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150612/6626a8ee/attachment.html>


More information about the es-discuss mailing list