How to get base domain from the URL in JavaScript

后端 未结 9 521
萌比男神i
萌比男神i 2020-12-06 02:52

I would like to extract the base domain from the url in javascript. For example for the list of urls listed below I need to get google.com (or googl

9条回答
  •  萌比男神i
    2020-12-06 03:22

    This depends on just how rigorous you need to be. The full list of valid top-level domains is given here, but the rules given here are possibly more helpful.

    A simple, probably incomplete regex:

    /[-\w]+\.(?:[-\w]+\.xn--[-\w]+|[-\w]{3,}|[-\w]+\.[-\w]{2})$/i
    

    Usage is something like this (I'm not great with Javascript regex):

    var match = HOSTDOMAIN.exec('www.google.co.in');
    if (match == null) {
        alert('not a valid domain!');
    } else {
        domain = match[0];
    }
    

提交回复
热议问题