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

來源:互聯網
上載者:User

標籤:

我們可能都知道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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.