How to break a regex in JavaScript

  String.prototype.is_email = function() {
      return this.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/);
  };

I am trying to get all my javascript files to tint linter ( http://code.google.com/closure/utilities/docs/linter_howto.html ); how to break a regex using the syntax / regex /.

Line 24, E: 0110: line too long (200 characters). Found 1 errors, including 0 new errors, in 1 file (0 files in order).

+3
source share
3 answers

You can use RegExp(pattern, modifiers)and pass the template as a string. A string can be created in small parts using concatenation.

+6
source

: regexp ( ), , \ {0} , , -...

var regex = /abc\
{0}def/;

regex.test("abcdef")   // true
regex.text("abc\ndef") // false
+2

I wrote a simple function to combine regular expressions to make them debugging a bit more manageable.

  var joinRegExp = function() {
    var args = Array.prototype.slice.call(arguments);
    return new RegExp(args.reduce(function(str, exp) {
      return str + exp.toString().replace(/\//g, '');
    }, ''));
  };

So, you can break your expression into something like that.

var local = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+/;
var localOpt = /(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*/;
var domain = /(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+/;
var tld = /(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/;

And join them.

var emailPattern = joinRegExp(local, localOpt, /@/, domain, tld);

You can check out this plunk for a demonstration.

0
source

Source: https://habr.com/ru/post/1779798/


All Articles