Skip to content

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

参数

参数名类型必填说明
urlstring要解析的URL字符串

返回值

类型说明
ParsedUrl解析后的URL对象

ParsedUrl 属性

属性名类型说明示例
protocolstring协议'https:'
hoststring主机(含端口)'example.com:8080'
hostnamestring主机名'example.com'
portstring端口号'8080'
pathnamestring路径'/path/to/page'
searchstring查询字符串'?foo=bar&baz=qux'
queryRecord<string, string>查询参数对象{ foo: 'bar', baz: 'qux' }
hashstring哈希值'#section'

异常

错误类型触发条件错误信息
Error无效的URL格式'Invalid URL'

工作原理

  1. 使用正则表达式匹配URL的各个部分
  2. 提取protocol、host、pathname、search、hash
  3. 从host中分离hostname和port
  4. 解析查询字符串为键值对象
  5. 对查询参数进行URL解码
  6. 返回包含所有信息的对象

使用示例

完整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) // '搜索'(自动解码)