標籤:
我們可能都知道javascript中的window.location對象用來擷取當前頁面的地址URL,並把瀏覽器重新導向到新的頁面。它有protocol、hostname、host、port、search、hash、href、pathname等屬性
比如:
window.location.href返回的是當前頁面的整個URL
window.location.hostname返回的是web主機的網域名稱
window.location.pathname返回的是當前頁面的路徑和檔案名稱
還有一個window.location.assign()方法,傳入的是一個URL地址,用來載入新的文檔。
很少人會知道的是a標籤也和window.location一樣也有這樣屬性,可以方便我們分析網址。因為html中的<a>標籤每出現一次,就會建立一個Anchor對象
代碼如下:
function parseURL(url) {var a = document.createElement(‘a‘);a.href = url;return {source: url,protocol: a.protocol.replace(‘:‘,‘‘),host: a.hostname,port: a.port||‘80‘,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;})(),file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,‘‘])[1],hash: a.hash.replace(‘#‘,‘‘),path: a.pathname.replace(/^([^\/])/,‘/$1‘),relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,‘‘])[1],segments: a.pathname.replace(/^\//,‘‘).split(‘/‘)};}
小技巧之a標籤自動解析URL