nunnly / everycode

Javascript 每日一练
116 stars 26 forks source link

获取网址的domain #47

Open nunnly opened 7 years ago

nunnly commented 7 years ago

Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:

domainName("http://github.com/carbonfive/raygun") == "github" 
domainName("http://www.zombie-bites.com") == "zombie-bites"
domainName("https://www.cnet.com") == "cnet"
domainName("https://www.cnet.cn/test.html") == "cnet"
domainName("https://test.cnet.cn") == "cnet"
Gxiangyu commented 7 years ago
function domainName(url) {
  var a = document.createElement('a');
  a.href = url;
  var l = a.hostname.split('.');
  if(l.length > 2){
    return l[1];
  }else{
    return l[0]
  }
}
weichenguang commented 7 years ago
function domainName(url) {
    var patt1 = /(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/;
    var str = url.match(patt1)[2]
    var arr = str.split(".")
    return arr.length == 3? arr[1] : arr[0]
  }
nunnly commented 7 years ago

@Gxiangyu 请不要使用BOM相关API,用纯javascript

SummerWind-July commented 7 years ago
// Written by xlm
function domainName(url){
        var index = url.indexOf('//');
        url = url.substring(index+2);
        var index2  = url.indexOf('/');
        if (index2!=-1){
            url = url.substring(0,index2);
        }
        var index3 = url.indexOf('.');
        var index4 = url.indexOf('.',index3+1);
        if (index4!=-1){
            url = url.substring(index3+1,index4);
        }else {
            url = url.substring(0,index3);
        }
        return url;
    }
zane277 commented 7 years ago
function domainName(url){
    var newUrl=url.split("//")[1]
    // console.log(newUrl)
    var newUrl=newUrl.split("/")[0]
    // console.log(newUrl)
    var newUrl = newUrl.split('.');
    // console.log(newUrl)
    var newUrl = newUrl[newUrl.length - 2];
    console.log(newUrl)
}
Caocp commented 7 years ago
function domainName(name){
    var a = name.split("/");
    var b = a[2].toString();
    var c = b.split(".");
    var d = c[c.length - 2].toString();
    document.write(d+"</br>");
  }
Robin-front commented 7 years ago
function domainName(url) {
    var reg = /(\w+:\/\/)?([^/:?#&]+)/;
    var str = url.match(reg)[2];
    var arr = str.split(".");
    return arr[arr.length-2];
  }

add case:

domainName("https://test.taobao.com") == "taobao"
domainName("https://test.taobao.com?v=123") == "taobao"
domainName("https://test.taobao.com#1") == "taobao"
domainName("https://h5api.m.taobao.com") == "taobao"
domainName("https://test.taobao.com:8080") == "taobao"

但不支持国家或地区二级域 : .com.cn .co.uk

function domainName(url, secondLevel) {
    var reg = /(\w+:\/\/)?([^/:?#&]+)/;
    var str = url.match(reg)[2];
    var arr = str.split(".");
    return !secondLevel ? arr[arr.length-2] : arr[arr.length-3];
  }

domainName("https://test.taobao.com.cn", true) == "taobao"