modifyUrlParam(data = {}, url = window.location.href) {
const singleCallBack = (_url, _key, _value) => {
const parsedUrl = new URL(_url)
const _params = new URLSearchParams(parsedUrl.search)
const regex = new RegExp(`([?&])${_key}=[^&]*`)
const modifiedUrl = _url.replace(regex, (match, prefix) => {
_params.set(_key, _value)
return prefix + _params.toString()
})
return modifiedUrl
}
if (Object.prototype.toString.call(data) === '[object Object]') {
const keys = Object.keys(data)
keys.forEach((key) => url = singleCallBack(url, key, data[key]))
} else if (Array.isArray(data)) {
data.forEach((item) => url = singleCallBack(url, item.key, item.value))
}
return url
}
let url = 'https://www.baidu.com/#/?brand=apple&shopId=1000000127'
const params = { brand: '111', shopId: '1000000128' }
const params_newUrl = modifyUrlParam(url, params)
console.log(params_newUrl)
const arr = [
{ key: 'brand', value: '222' },
{ key: 'shopId', value: '1000000129' }
]
const arr_newUrl = modifyUrlParam(url, arr)
console.log(arr_newUrl)