How to split a long regular expression into multiple lines in JavaScript?

I have a very long regular expression, which I wish to split into multiple lines in my JavaScript code to keep each line length 80 characters according to JSLint rules. It’s just better for reading, I think. Here’s pattern sample:

var pattern = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;

Answer

You could convert it to a string and create the expression by calling new RegExp():

var myRE = new RegExp (['^(([^<>()[]\.,;:\s@"]+(\.[^<>(),[]\.,;:\s@"]+)*)',
                        '|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.',
                        '[0-9]{1,3}])|(([a-zA-Z-0-9]+\.)+',
                        '[a-zA-Z]{2,}))$'].join(''));

Notes:

  1. when converting the expression literal to a string you need to escape all backslashes as backslashes are consumed when evaluating a string literal. (See Kayo’s comment for more detail.)
  2. RegExp accepts modifiers as a second parameter

    /regex/g => new RegExp('regex', 'g')

[Addition ES20xx (tagged template)]

In ES20xx you can use tagged templates. See the snippet.

Note:

  • Disadvantage here is that you can’t use plain whitespace in the regular expression string (always use s, s+, s{1,x}, t, n etc).

(() => {
  const createRegExp = (str, opts) => 
    new RegExp(str.raw[0].replace(/s/gm, ""), opts || "");
  const yourRE = createRegExp`
    ^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|
    (".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|
    (([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$`;
  console.log(yourRE);
  const anotherLongRE = createRegExp`
    (byyyyb)|(bmb)|(bdb)|(bhb)|(bmib)|(bsb)|(bmsb)|
    (bwdb)|(bmmb)|(bddb)|(bhhb)|(bMIb)|(bSb)|(bMSb)|
    (bMb)|(bMMb)|(bdowb)|(bDOWb)
    ${"gi"}`;
  console.log(anotherLongRE);
})();