Search code examples
javascriptregexsubdomain

Combine two regular expression that check an url into one


This is my code to check the url is subDomain or not .

    var domain_1 = "abc.mydomain.com";
    var domain_2 = "abc.localhost:44880"

    var regex1 = new RegExp(/^([a-z]+\:\/{2})?([\w-]+\.[\w-]+\.\w+)$/);
    var regex2 = new RegExp(/^([a-z]+\:\/{2})?([\w-]+\.[\w-]+\:\w+)$/);
   
    let result1 = !!domain_1.match(regex1);
    let result2 = !!domain_2.match(regex2);

As you can see, the format for first subDomain is like ###.###.### (with two dots) second one is ###.###:### (with one dot and one colon).
For those two format , I need two Regular Expressions.
Can I combine it to one ?


Solution

  • This takes care of single word (localhost) to many dot separated words (abc.many.subs.mydomain.com) for the domain name, making sure that there are no consecutive dots, followed by an optional port number (:1234) :

    const domains = [
      'abc.mydomain.com',
      'abc.localhost:44880',
      'localhost',
      'abc.many.subs.mydomain.com',
      'abc.my@domain.com',
      'abc.my@domain.com:1234'
    ];
    const regex = /^[a-z_\-]+(\.[a-z_\-]+)*(\:[0-9]+)?$/;
    domains.forEach((domain) => {
      var result = regex.test(domain);
      console.log(domain + ' ==> ' + result)
    });

    Console output:

    abc.mydomain.com ==> true
    abc.localhost:44880 ==> true
    localhost ==> true
    abc.many.subs.mydomain.com ==> true
    abc.my@domain.com ==> false
    abc.my@domain.com:1234 ==> false
    

    Explanation:

    • ^...$ - anchor regex at start and end
    • [a-z_\-]+ - start with a word of one or more allowed chars
    • (\.[a-z_\-]+)* - followed by zero or more occurrences of a dot and a word
    • (\:[0-9]+)? - followed by an optional dot and at least one digit