验证url并检查url是域还是子域

时间:2013-02-01 10:59:04

标签: javascript validation 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 -> false 

subdomain.mydomain.com -> true

mydomain.com. -> true

2 个答案:

答案 0 :(得分:4)

你可以在一个正则表达式中实际测试它,例如:

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

答案 1 :(得分: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())
}