js中url相關

來源:互聯網
上載者:User

標籤:object   keyword   search   dir   無語   pre   prot   rip   regex   

首先看一個解析url的函數,網址各部分一般格式為http://domain.com/?search=a#hash

function parseURL(url) { var a = document.createElement(‘a‘); /造一個a元素 a.href = url; //a的連結為url return { source: url, protocol: a.protocol.replace(‘:‘,‘‘),//協議,把冒號換成空格 host: a.hostname, //主機名稱 port: a.port, //連接埠 query: a.search, //問號及問號後面的 params: (function(){ var ret = {}, seg = a.search.replace(/^\?/,‘‘).split(‘&‘),、//把query裡面的問號改為空白格,並以數組形式返回,按&分隔。在下例中得到id=225 m=hello len = seg.length, i = 0, s; for (i;i<len;i++) { if (!seg[i]) { continue; }//沒有seach則忽略 s = seg[i].split(‘=‘);//否則按等號隔開 ret[s[0]] = s[1]; id=225 m=hellow } return ret;返回上面所求 })(), file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,‘‘])[1], //pathname為路徑名,port後面,search前面,zRegex有點亂,頭大,以後再分析 hash: a.hash.replace(‘#‘,‘‘),//#top變為top path: a.pathname.replace(/^([^\/])/,‘/$1‘),//繼續亂 relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,‘‘])[1], segments: a.pathname.replace(/^\//,‘‘).split(‘/‘)//無語,看不下去了 };}

var myURL = parseURL(‘http://abc.com:8080/dir/index.html?id=255&m=hello#top‘); myURL.file; // = ‘index.html‘myURL.hash; // = ‘top‘myURL.host; // = ‘abc.com‘myURL.query; // = ‘?id=255&m=hello‘myURL.params; // = Object = { id: 255, m: hello }myURL.path; // = ‘/dir/index.html‘myURL.segments; // = Array = [‘dir‘, ‘index.html‘]myURL.port; // = ‘8080‘myURL.protocol; // = ‘http‘myURL.source; // = ‘http://abc.com:8080/dir/index.html?id=255&m=hello#top‘
 

js中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.