28 lines
852 B
TypeScript
28 lines
852 B
TypeScript
export function appendParamsToUrl(url = '', pathname = '', params: Record<string, string> = {}) {
|
||
// 创建一个新的URL对象,在末尾添加 pathname
|
||
const urlObject = new URL(pathname, url)
|
||
|
||
// 获取该URL的查询参数对象
|
||
const searchParams = new URLSearchParams(urlObject.search)
|
||
|
||
// 添加新的参数
|
||
for (const key in params) {
|
||
searchParams.append(key, params[key])
|
||
}
|
||
// 设置URL的查询参数
|
||
let result = urlObject.toString()
|
||
if (result.endsWith('?') || result.endsWith('&')) {
|
||
result += searchParams.toString()
|
||
} else if (result.indexOf('?') > -1) {
|
||
if (result.endsWith('&')) {
|
||
result += searchParams.toString()
|
||
} else {
|
||
result += '&' + searchParams.toString()
|
||
}
|
||
} else {
|
||
result += '?' + searchParams.toString()
|
||
}
|
||
// 返回处理后的URL字符串
|
||
return result
|
||
}
|