解析URL的主机名

字符串 http://www.abc.com/a/b?name=ss,返回字符串www.abc.com

function parseURL(url) {
 var a =  document.createElement('a');
 a.href = url;
 return {
 source: url,
 protocol: a.protocol.replace(':',''),
 host: a.hostname,
 port: a.port,
 query: a.search,
 params: (function(){
     var ret = {},
         seg = a.search.replace(/^\?/,'').split('&'),
         len = seg.length, i = 0, s;
     for (;i<len;i++) {
         if (!seg[i]) { continue; }
         s = seg[i].split('=');
         ret[s[0]] = s[1];
     }
     return ret;
 })(),
 hash: a.hash.replace('#',''),
 path: a.pathname

 };
}

var myURL = parseURL('http://www.abc.com:8080/dir/index.html?id=255&m=hello#top');
console.log('host=='+myURL.host);

  

posted on 2017-05-07 21:54  十八般武艺  阅读(328)  评论(0编辑  收藏  举报