Skip to content

@longmo-utils/browser / getURLSearchParams

Function: getURLSearchParams()

ts
function getURLSearchParams(url?): Record<string, string>;

获取 URL 中的查询参数

支持从当前页面 URL 或指定 URL 中提取查询参数

Parameters

ParameterTypeDescription
url?string要解析的 URL 字符串。如果不提供,则使用当前页面 URL

Returns

Record<string, string>

返回包含所有查询参数的对象

Examples

typescript
// 当前 URL: https://example.com?page=1&sort=desc&filter=active
const params = getURLSearchParams();
console.log(params); // { page: '1', sort: 'desc', filter: 'active' }
typescript
const url = 'https://example.com/search?q=hello&lang=zh-CN';
const params = getURLSearchParams(url);
console.log(params); // { q: 'hello', lang: 'zh-CN' }
typescript
const params = getURLSearchParams();
const page = params.page; // '1'
const count = parseInt(params.count || '0'); // 带默认值转换
typescript
// URL: https://example.com?id=1&id=2&id=3
const params = getURLSearchParams('https://example.com?id=1&id=2&id=3');
console.log(params.id); // '3'(取最后一个)
typescript
const params = getURLSearchParams('https://example.com');
console.log(params); // {}

Released under the MIT License.