buildQueryString
将对象转换为URL查询字符串
参数配置
=
=
=
选项
预设模板
生成结果
page=1&limit=10&search=hello%20world 长度: 36 字符
函数签名
typescript
interface BuildQueryStringOptions {
prefix?: boolean
skipNull?: boolean
}
function buildQueryString(
params: Record<string, any>,
options?: BuildQueryStringOptions
): string参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
params | Record<string, any> | 是 | 参数对象 |
options | BuildQueryStringOptions | 否 | 可选配置 |
BuildQueryStringOptions
| 属性名 | 类型 | 默认值 | 说明 |
|---|---|---|---|
prefix | boolean | false | 是否添加 ? 前缀 |
skipNull | boolean | true | 是否跳过 null 和 undefined 值 |
返回值
| 类型 | 说明 |
|---|---|
string | 查询字符串 |
工作原理
- 遍历参数对象的所有键值对
- 根据 skipNull 选项决定是否跳过 null/undefined 值
- 对键和值进行 URL 编码
- 用
=连接键值对 - 用
&连接所有键值对 - 根据 prefix 选项决定是否添加
?前缀
使用示例
基本用法
typescript
buildQueryString({ foo: 'bar', baz: 'qux' })
// 'foo=bar&baz=qux'
buildQueryString({ foo: 'bar' }, { prefix: true })
// '?foo=bar'处理特殊字符
typescript
buildQueryString({
name: 'hello world',
city: '北京'
})
// 'name=hello%20world&city=%E5%8C%97%E4%BA%AC'处理空值
typescript
buildQueryString({
foo: 'bar',
baz: null,
qux: undefined
})
// 'foo=bar'(默认跳过null和undefined)
buildQueryString({
foo: 'bar',
baz: null
}, { skipNull: false })
// 'foo=bar&baz=null'构建完整URL
typescript
const baseUrl = 'https://api.example.com/users'
const params = { page: 1, limit: 10, role: 'admin' }
const queryString = buildQueryString(params, { prefix: true })
const fullUrl = baseUrl + queryString
// 'https://api.example.com/users?page=1&limit=10&role=admin'