parseUrl
解析URL字符串
URL 输入
解析结果
Protocol
https:
Host
example.com:8080
Hostname
example.com
Port
8080
Pathname
/path/to/page
Search
?foo=bar&baz=qux&page=1
Hash
#section
查询参数
foo
bar
baz
qux
page
1
函数签名
typescript
interface ParsedUrl {
protocol: string
host: string
hostname: string
port: string
pathname: string
search: string
query: Record<string, string>
hash: string
}
function parseUrl(url: string): ParsedUrl参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
url | string | 是 | 要解析的URL字符串 |
返回值
| 类型 | 说明 |
|---|---|
ParsedUrl | 解析后的URL对象 |
ParsedUrl 属性
| 属性名 | 类型 | 说明 | 示例 |
|---|---|---|---|
protocol | string | 协议 | 'https:' |
host | string | 主机(含端口) | 'example.com:8080' |
hostname | string | 主机名 | 'example.com' |
port | string | 端口号 | '8080' |
pathname | string | 路径 | '/path/to/page' |
search | string | 查询字符串 | '?foo=bar&baz=qux' |
query | Record<string, string> | 查询参数对象 | { foo: 'bar', baz: 'qux' } |
hash | string | 哈希值 | '#section' |
异常
| 错误类型 | 触发条件 | 错误信息 |
|---|---|---|
Error | 无效的URL格式 | 'Invalid URL' |
工作原理
- 使用正则表达式匹配URL的各个部分
- 提取protocol、host、pathname、search、hash
- 从host中分离hostname和port
- 解析查询字符串为键值对象
- 对查询参数进行URL解码
- 返回包含所有信息的对象
使用示例
完整URL解析
typescript
const url = 'https://example.com:8080/path?foo=bar&baz=qux#hash'
const parsed = parseUrl(url)
// {
// protocol: 'https:',
// host: 'example.com:8080',
// hostname: 'example.com',
// port: '8080',
// pathname: '/path',
// search: '?foo=bar&baz=qux',
// query: { foo: 'bar', baz: 'qux' },
// hash: '#hash'
// }获取查询参数
typescript
const url = 'http://localhost:3000/api/users?page=1&limit=10'
const { query } = parseUrl(url)
console.log(query.page) // '1'
console.log(query.limit) // '10'处理中文URL
typescript
const url = 'https://example.com/search?q=%E6%90%9C%E7%B4%A2'
const { query } = parseUrl(url)
console.log(query.q) // '搜索'(自动解码)