標籤: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相關