「站在巨人的肩膀上」html
靈感來源:web
https://segmentfault.com/a/1190000004601319
和segmentfault
http://mp.weixin.qq.com/mp/ad_biz_info?__biz=MzAwMjU3OTY5NQ==#wechat_webview_type=2&wechat_redirect
上面一個地址,可讓你學到如何解析一個url地址,從中解析出每個參數內容
第二個連接的問題就是參數中的鍵值對出現了==號,這是base64信息,若是再用=切割,就會出問題,這裏就改版了一下瀏覽器
String.prototype.parseURL = function(){ var url =this.toString() var a = document.createElement('a'); a.href = url; return { source: url, protocol: a.protocol.replace(':', ''), host: a.hostname, port: a.port, query: a.search, 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('/'), params: (function() { var ret = {}; var seg = a.search.replace(/^\?/, '').split('&').filter(function(v,i){ if (v!==''&&v.indexOf('=')) { return true; } }); seg.forEach( function(element, index) { var idx = element.indexOf('='); var key = element.substring(0, idx); var val = element.substring(idx+1); ret[key] = val; }); return ret; })() }; }
調用方法:測試
location.href.parseURL(); 'http://a.com:8888/a/b.html?c=1&0=0&d===&=1'.parseURL(); //上面故意把參數寫的很亂,爲了測試,若是上面你的瀏覽器報錯,說明版本較低,能夠以下寫法 ('http://a.com:8888/a/b.html?c=1&0=0&d===&=1').parseURL();