参数定义:
- url: url地址参数;
- params:需要拼接或修改的参数对象列表
/**
* 给url后面动态拼接参数或修改参数
* @param url
* @param params
*/
function changeURLArg(url, params) {
let resUrl = url || ''
if (url && params) {
Object.keys(params).forEach((key, index) => {
if (params[key]) {
const regExp = new RegExp(`(${key}=)([^&]*)`, 'ig')
if (regExp.test(resUrl)) {
resUrl = resUrl.replace(regExp, `${key}=${params[key]}`)
} else {
let splitStr = '&'
if (index === 0) {
if (url.indexOf('?') === -1) {
splitStr = '?'
}
}
resUrl += `${splitStr}${key}=${params[key]}`
}
}
})
}
return resUrl
}
示例如下:
const url = 'https://www.jianshu.com?a=2'
const params = {
a: 1,
b: 2
}
const newUrl = changeURLArg(url, params) // https://www.jianshu.com?a=1&b=2