js獲取url地址中的每一個引數,方便操作url的hash
阿新 • • 發佈:2018-10-31
js獲取url地址中的每一個引數,方便操作url的hash
值得收藏
<html> <body> <script> //location.search; //可獲取瀏覽器當前訪問的url中"?"符後的字串 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'),//將該字串首位不是/的用這個組([^\/])替換,$1代表出現在正則表示式中的第一個()、$2代表出現在正則表示式中的第二個()... relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1], segments: a.pathname.replace(/^\//,'').split('/') }; } var URL = parseURL('http://abc.com:8080/dir/index.html?pid=255&m=hello#top&ab=1'); // var URL = parseURL('http://localhost:8080/test/mytest/toLogina.ction?m=123&pid=abc'); console.log('URL.query', URL.query) console.log('URL.path', URL.path); console.log('URL.hash', URL.hash); console.log('URL.params.pid', URL.params.pid); </script> </body> </html>
參考:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace