/*
解析URL地址
parsURL( url ).file; // = ‘index.html‘
parsURL( url ).hash; // = ‘top‘
parsURL( url ).host; // = ‘www.abc.com‘
parsURL( url ).query; // = ‘?id=255&m=hello‘
parsURL( url ).queryURL // = ‘id=255&m=hello‘
parsURL( url ).params; // = Object = { id: 255, m: hello }
parsURL( url ).prefix; // = ‘www‘
parsURL( url ).path; // = ‘/dir/index.html‘
parsURL( url ).segments; // = Array = [‘dir‘, ‘index.html‘]
parsURL( url ).port; // = ‘8080‘
parsURL( url ).protocol; // = ‘http‘
parsURL( url ).source; // = ‘http://www.abc.com:8080/dir/index.html?id=255&m=hello#top‘
*/
function parsURL( url ) {
var a = document.createElement(‘a‘);
a.href = 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(‘&‘),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;
})(),
queryURL:a.search.replace(/^\?/,‘‘),
prefix: a.hostname.split(‘.‘)[0],
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(‘/‘)
};
}
原文:http://my.oschina.net/arts1986/blog/483930