在使用URL
轉換鏈接的時候度陆,query
無法很直觀的體現锻全,且想要根據key
獲取值的時候不方便狭瞎,
如果導入jsuri等工具解析又太復雜党窜,使用起來也麻煩
所以考慮使用js的原始屬性new URL在保留URL
的用法的同時,改動最小的情況下点把,增加一個對象形式的query
- 糾正與兼容用戶拼接了多個?的情況
- 無傳入數據時橘荠,使用當前的location.href解析
如下圖:
search
內的?q=books?name=簡書&id=10087都能順利解析
image.png
const _URL = URL
window.URL = function (url, base) {
url = url || location.href
let u = new _URL(url, base)
if (u) {
function get() {
let s = u.search
let arr = {}
if (s) {
s = s.substring(1).replace(/\?/g, '&').split('&')
s.forEach(item => {
let t = item.split('=')
arr[t[0]] = decodeURIComponent(t[1] || '')
})
}
return arr
}
u.query = get()
}
return u
}
let url = new URL('https://user:pass@www.test.com:81/index.html?q=books?name=簡書&id=10087#fragment')
console.log(url)
console.log(url.query.name)