JS获取url参数

166 阅读1分钟

获取url参数

方案一:

function getQueryString() {
    const s = window.location.search
    const list = s.split('&')
    const obj = {}
    list.forEach(item => {
        let arr = item.split('=')
        obj[arr[0]] = arr[1]
    })
    return obj
}

方案二:

function getQueryString() {
    const s = window.location.search
    const qs = new URLSearchParams(s)
    const obj = {}
    
    for (const p of qs.entries()) {
        obj[p[0]] = p[1]
    }
    
    return obj
}
const href = window.location.href
const args = href.split('?')

=

const s = window.location.search

比如:

当前地址是: http://127.0.0.1/index.html?a=1&b=2&c=3

返回的是
{
    a: 1,
    b: 2,
    c: 3
}