javascript parseUrl函數(shù)(來自國外的獲取網(wǎng)址url參數(shù))
更新時間:2010年06月12日 21:39:02 作者:
在外國一博客看到一個很好的函數(shù),獲取網(wǎng)址url等地址參數(shù)。非常不錯,值得參考與收藏。
函數(shù)代碼
function parseURL(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;
})(),
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('/')
};
}
用法:
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'
演示代碼:
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
復制代碼 代碼如下:
function parseURL(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;
})(),
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('/')
};
}
用法:
復制代碼 代碼如下:
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'
演示代碼:
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
相關文章
sencha touch 模仿tabpanel導航欄TabBar的實例代碼
這篇文章介紹了sencha touch 模仿tabpanel導航欄TabBar的實例代碼,有需要的朋友可以參考一下2013-10-10關于在IE下的一個安全BUG --可用于跟蹤用戶的系統(tǒng)鼠標位置
本篇文章小編將為大家介紹,關于在IE下的一個安全BUG --可用于跟蹤用戶的系統(tǒng)鼠標位置。需要的朋友可以參考一下2013-04-04純js實現(xiàn)div內(nèi)圖片自適應大小(已測試,兼容火狐)
純js實現(xiàn)在img圖片大小未知,div大小未知的情況下,讓圖片自適應大小,需要的朋友可以參考下2014-06-06用html5 js實現(xiàn)點擊一個按鈕達到瀏覽器全屏效果
點擊一個按鈕要實現(xiàn)按F11全屏的效果。 在HTML5中,W3C制定了關于全屏的API,就可以實現(xiàn)全屏幕的效果2014-05-05