利用a標簽自動解析URL分析網(wǎng)址實例
更新時間:2014年10月20日 16:03:04 投稿:whsnow
a標簽也和window.location一樣,也有這樣屬性,因此可以利用它來分析網(wǎng)址,下面的實例代碼,大家可以看看
對于window.location,我們比較熟悉,它有protocol,hostname,host,port,search,hash,href,pathname等屬性,a標簽也和window.location一樣,也有這樣屬性,這樣可以方便我們分析網(wǎng)址,閑話少說,上代碼。
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('/') }; }
測試地址
console.log(parseURL("http://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2"));
結(jié)果如下
復制代碼 代碼如下:
{
file: "dom_obj_anchor.asp",
hash: "id2",
host: "www.w3school.com.cn",
params: {type: "2"},
path: "/jsref/dom_obj_anchor.asp",
port: "80",
protocol: "http",
query: "?type=2",
relative: "/jsref/dom_obj_anchor.asp?type=2#id2",
segments: [0: "jsref",1: "dom_obj_anchor.asp"],
source: http://www.w3school.com.cn/jsref/dom_obj_anchor.asp?type=2#id2
}
相關(guān)文章
javascript Table 中2個列(TD)的交換實現(xiàn)代碼
非常不錯的用js控制talbe中td的位置的實現(xiàn)代碼。2009-02-02JS設(shè)置隨機出現(xiàn)2個數(shù)字的實例代碼
這篇文章給大家分享基于js設(shè)置隨機出現(xiàn)2個數(shù)字的實例代碼,在文章下面給分享js產(chǎn)生隨機數(shù)的幾個用法介紹,感興趣的朋友一起看看吧2017-07-07