小技巧之a標簽自動解析URL


我們可能都知道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('/')
};
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM