4

我需要验证 URL 并检查输入的 URL 是域还是子域。
我尝试了一个解决方案,它可以工作,但在某些情况下它失败了。

function subDomain(url) 
{

    // IF THERE, REMOVE WHITE SPACE FROM BOTH ENDS
    url = url.replace(new RegExp(/^\s+/),""); // START
    url = url.replace(new RegExp(/\s+$/),""); // END

    // IF FOUND, CONVERT BACK SLASHES TO FORWARD SLASHES
    url = url.replace(new RegExp(/\\/g),"/");

    // IF THERE, REMOVES 'http://', 'https://' or 'ftp://' FROM THE START
    //url = url.replace(new RegExp(/^http\:\/\/|^https\:\/\/|^ftp\:\/\//i),"");

    // IF THERE, REMOVES 'www.' FROM THE START OF THE STRING
    url = url.replace(new RegExp(/^www\./i),"");

    // REMOVE COMPLETE STRING FROM FIRST FORWARD SLASH ON
    url = url.replace(new RegExp(/\/(.*)/),"");

    // REMOVES '.??.??' OR '.???.??' FROM END - e.g. '.CO.UK', '.COM.AU'
    if (url.match(new RegExp(/\.[a-z]{2,3}\.[a-z]{2}$/i))) {
        url = url.replace(new RegExp(/\.[a-z]{2,3}\.[a-z]{2}$/i),"");

    // REMOVES '.??' or '.???' or '.????' FROM END - e.g. '.US', '.COM', '.INFO'
    } else if (url.match(new RegExp(/\.[a-z]{2,4}$/i))) {
        url = url.replace(new RegExp(/\.[a-z]{2,4}$/i),"");
    }

    // CHECK TO SEE IF THERE IS A DOT '.' LEFT IN THE STRING
    var subDomain = (url.match(new RegExp(/\./g))) ? true : false;
    return(subDomain);
}

结果:

 
mydomain.com -> 假

subdomain.mydomain.com -> 真

mydomain.com。-> 真的
4

2 回答 2

6

您实际上可以在一个正则表达式中对此进行测试,例如:

var isSubdomain = function(url) {
    url = url || 'http://www.test-domain.com'; // just for the example
    var regex = new RegExp(/^([a-z]+\:\/{2})?([\w-]+\.[\w-]+\.\w+)$/);

    return !!url.match(regex); // make sure it returns boolean
}

console.log(isSubdomain("example.com"));
console.log(isSubdomain("http://example.com:4000"));
console.log(isSubdomain("www.example.com:4000"));
console.log(isSubdomain("https://www.example.com"));
console.log(isSubdomain("sub.example.com"));
console.log(isSubdomain("example.co.uk")); //it doesn't work on these very specific cases

于 2013-02-01T11:20:53.227 回答
0

您可以只使用 URI 来执行此操作。 https://medialize.github.io/URI.js/docs.html

const subdomain = new URI('https://stackoverflow.com/questions/14644805/validate-url-and-check-if-url-is-domain-or-subdomain').subdomain()

subdomain // Will be an empty string if no subdomain exists

然后在函数中使用它

function isSubdomain(url) {
  return Boolean(new URI(url).subdomain())
}
于 2020-06-29T08:45:49.530 回答