2012年3月7日星期三

Javascript获取URL的顶级域名(get top domain)

JS现成的方法只能通过location.hostname或者document.domain得到URL的domain,但是这个domain可能是顶级的,但也有可能二级、三级的,要取得主域名只能自己写,今天看到一个转过来:

function  getDomain(){
   var domain = window.location.host;
   var pat = /^www\.(\.+)/;
   var _match = domain.match(pat);
   if(_match !== null){
    return _match[1];
   };
   var ret = null;
   var ext = ["com\.cn","net\.cn","org\.cn","gov\.cn","com\.hk","co\.uk","com","net","org","int","edu","gov","mil","arpa","Asia","biz","info","name","pro","coop","aero","museum","ac","ad","ae","af","ag","ai","al","am","an","ao","aq","ar","as","at","au","aw","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bm","bn","bo","br","bs","bt","bv","bw","by","bz","ca","cc","cf","cg","ch","ci","ck","cl","cm","cn","co","cq","cr","cu","cv","cx","cy","cz","de","dj","dk","dm","do","dz","ec","ee","eg","eh","es","et","ev","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gh","gi","gl","gm","gn","gp","gr","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","id","ie","il","in","io","iq","ir","is","it","jm","jo","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mg","mh","ml","mm","mn","mo","mp","mq","mr","ms","mt","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nt","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pm","pn","pr","pt","pw","py","qa","re","ro","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","st","su","sy","sz","tc","td","tf","tg","th","tj","tk","tm","tn","to","tp","tr","tt","tv","tw","tz","ua","ug","uk","us","uy","va","vc","ve","vg","vn","vu","wf","ws","ye","yu","za","zm","zr","zw"];
   var i = 0, l = ext.length;
   for(; i < l; i++){
    var val = ext[i];
    var expObj = null;
    eval("expObj = /^((\\w+\\.)+)(" + val + ")$/");
    var _tempMatch = domain.match(expObj);
    if(_tempMatch !== null){
     if(_tempMatch.length === 4){
      var domainExt = _tempMatch[3];
      var preFix = _tempMatch[1].replace(/(\.+)$/g, "");
      var preFixArr = preFix.split(".").reverse();
      ret = preFixArr[0] + "." + domainExt;
      break;
     };
    };
   };
   return ret;
  }

没有评论: