Skip to content

@longmo-utils/browser / setURLSearchParams

Function: setURLSearchParams()

ts
function setURLSearchParams(url?, params?): string;

给 URL 设置或更新查询参数

支持添加新参数、更新现有参数、删除参数

Parameters

ParameterTypeDescription
url?string要处理的 URL 字符串。如果不提供,则使用当前页面 URL
params?Record<string, string | undefined>要设置的查询参数对象

Returns

string

返回包含更新后查询参数的 URL

Examples

typescript
const url = 'https://example.com';
const newUrl = setURLSearchParams(url, { page: '1', sort: 'desc' });
console.log(newUrl); // 'https://example.com?page=1&sort=desc'
typescript
const url = 'https://example.com?page=1&sort=desc';
const newUrl = setURLSearchParams(url, { page: '2', filter: 'active' });
console.log(newUrl); // 'https://example.com?page=2&sort=desc&filter=active'
typescript
const url = 'https://example.com?page=1&sort=desc&filter=active';
const newUrl = setURLSearchParams(url, { filter: undefined });
console.log(newUrl); // 'https://example.com?page=1&sort=desc'
typescript
// 当前 URL: https://example.com?page=1
const newUrl = setURLSearchParams(undefined, { page: '2', size: '10' });
console.log(newUrl); // 'https://example.com?page=2&size=10'
typescript
const url = 'https://example.com/search';
const newUrl = setURLSearchParams(url, { q: 'hello world' });
console.log(newUrl); // 'https://example.com/search?q=hello%20world'

Released under the MIT License.