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,}))$/;
You can simply use string operation.
The regex above is missing some black slashes which isn't working properly. So, I edited the regex. Please consider this regex which works 99.99% for email validation.
You could convert it to a string and create the expression by calling
new RegExp()
:Notes:
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:
\s
,\s+
,\s{1,x}
,\t
,\n
etc).Using strings in
new RegExp
is awkward because you must escape all the backslashes. You may write smaller regexes and concatenate them.Let's split this regex
We will use a function to make things more beautiful later
And now let's rock
Since it has a cost, try to build the real regex just once and then use that.
Personally, I'd go for a less complicated regex:
Sure, it is less accurate than your current pattern, but what are you trying to accomplish? Are you trying to catch accidental errors your users might enter, or are you worried that your users might try to enter invalid addresses? If it's the first, I'd go for an easier pattern. If it's the latter, some verification by responding to an e-mail sent to that address might be a better option.
However, if you want to use your current pattern, it would be (IMO) easier to read (and maintain!) by building it from smaller sub-patterns, like this:
Extending @KooiInc answer, you can avoid manually escaping every special character by using the
source
property of theRegExp
object.Example:
or if you want to avoid repeating the
.source
property you can do it using theArray.map()
function:In ES6 the map function can be reduced to:
.map(r => r.source)