cmc-web/packages/common/utils/url.ts

28 lines
852 B
TypeScript
Raw Normal View History

2024-09-01 07:45:39 +00:00
export function appendParamsToUrl(url = '', pathname = '', params: Record<string, string> = {}) {
2024-09-01 06:56:37 +00:00
// 创建一个新的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的查询参数
2024-09-01 07:40:39 +00:00
let result = urlObject.toString()
2024-09-04 10:50:22 +00:00
if (result.endsWith('?') || result.endsWith('&')) {
2024-09-01 07:40:39 +00:00
result += searchParams.toString()
2024-09-04 10:50:22 +00:00
} else if (result.indexOf('?') > -1) {
if (result.endsWith('&')) {
result += searchParams.toString()
} else {
result += '&' + searchParams.toString()
}
2024-09-01 07:40:39 +00:00
} else {
result += '?' + searchParams.toString()
}
2024-09-01 06:56:37 +00:00
// 返回处理后的URL字符串
2024-09-01 07:40:39 +00:00
return result
2024-09-01 06:56:37 +00:00
}