今天遇到一個需要用javascript將url中的某些參數替換的需求:
var a = document.createElement( 'a' ); |
protocol: a.protocol.replace( ':' , '' ), |
seg = a.search.replace(/^\?/, '' ).split( '&' ), |
len = seg.length, i = 0, s; |
if (!seg[i]) { continue ; } |
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://www.21kaiyun.com/default.aspx?id=255&m=hello#top' ); |
myURL.file; // = 'index.html' |
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.protocol; // = 'http' |
myURL.source; // = 'http://www.21kaiyun.com |
取得URL的參數,以對象形式返回!
var getParam = function (path){ |
var result = {},param = /([^?=&]+)=([^&]+)/ig,match; |
while ((match = param.exec(path)) != null ){ |
result[match[1]] = match[2]; |
Object.keys = Object.keys || function (obj){ |
if (obj.hasOwnProperty(i)){ |
var path = "http://www.21kaiyun.com/f?ct=318767104&tn=baiduKeywordSearch&sc=1&pn=0&rn=50&lm=4&rs4=2&rs3=2&word=%D0%C2%BE%D3%D5%D1%C4%CB&frs=jpq" ; |
alert(Object.keys(r)) //ct,tn,sc,pn,rn,lm,rs4,rs3,word,frs |