js--如何获取url上的参数(封装)

1.创建utils/UrlParser.js

// 增加新参数
export const appendParam = (url, param, isSearch = true, isHash = true) => {
    const urlObj = parseUrl(url)
    isSearch && (urlObj.search = searchHashAppend(urlObj.search, param))
    isHash && (urlObj.hash && searchHashAppend(urlObj.hash, param) || '')
    const { originPath, search, hash } = urlObj
    return `${originPath}${search}${hash}`
}

export const searchHashAppend = (target, append, filterEmpty) => {
    const param = paramStrToObj(target) || {}
    Object.assign(param, append)
    const paramStr = param && objToUrlParamStr(param, filterEmpty) || ''
    const idx = target.indexOf('?')
    const prefix = idx > -1 && target.substring(0, idx + 1) || `${target}?`
    return `${prefix}${paramStr}`
}


export const objToUrlParamStr = (param, filterEmpty = true) => {
    return objToUrlParamEncodeStr(param, filterEmpty, false)
}

export const objToUrlParamEncodeStr = (param, filterEmpty = true, encode = true) => {
    const arrays = []
    for (const key in param) {
        const val = param[key] === 0 ? '0' : (param[key] || '');
        (!filterEmpty || val) && arrays.push(`${key}=${encode ? encodeURIComponent(val) : val}`)
    }

    return arrays.join('&')
}

// 把url参数转换成对象格式
export const paramStrToObj = (paramUrl) => {
    if (!paramUrl) return {}

    const arrays = paramUrl.split('?') || []
    const paramStr = arrays[1] || ''
    const vals = paramStr && paramStr.split('&') || []
    const res = {}
    vals.map(item => {
        const kvs = item.split('=') || []
        res[kvs[0]] = kvs[1]
    })

    return res
}

// 把hash和search组成一个新对象{ source:xx,originPath:xx,search:xx,hash:xx }
export const parseUrl = url => {
    const searchIdx = url.indexOf('?')
    const hashIdx = url.indexOf('#')
    const temp = { source: url, originPath: '', search: '', hash: '' }
    if (searchIdx < hashIdx) { // 存在hash部分,可能存在search
        if (searchIdx > -1) { // 存在search
            const originPath = url.substring(0, searchIdx)
            const search = url.substring(searchIdx, hashIdx)
            const hash = url.substring(hashIdx, url.length)
            Object.assign(temp, { originPath, search, hash })
        } else {
            const originPath = url.substring(0, hashIdx)
            const hash = url.substring(hashIdx, url.length)
            Object.assign(temp, { originPath, hash })
        }
    } else if (searchIdx > hashIdx) {
        if (hashIdx > 0) { // 不存在hash 但是存在search
            const originPath = url.substring(0, hashIdx)
            const hash = url.substring(hashIdx, url.length)
            Object.assign(temp, { originPath, hash })
        } else {
            const originPath = url.substring(0, searchIdx)
            const search = url.substring(searchIdx, url.length)
            Object.assign(temp, { originPath, search })
        }
    } else { // 不存在hash 也不存在search
        Object.assign(temp, { originPath: url })
    }

    return temp
}

2.如何使用

let test = appendParam(window.location.href, { temp: 111 })
let test1 = searchHashAppend(window.location.search)
let test2 = paramStrToObj(window.location.search)
console.log(test, '--->>>>测试成功','http://localhost:3520/index.html?channelCode=001&t=1684983911806&temp=111#/insu-detail')
console.log(test1, '--->>>>测试成功1','?channelCode=001&t=1684983911806')
console.log(test2, '--->>>>测试成功2','{baosicode: "BASE2023",channelCode: "001",t: "1684983911806"}')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值