All files / utils parseUrlQueryString.ts

92.86% Statements 13/14
91.67% Branches 11/12
100% Functions 1/1
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33                                    23x 22x 22x 22x 22x 22x 40x 40x 40x 40x 40x   22x    
import { CreateUrlQueryStringOptions } from './createUrlQueryString'
 
/**
 * 解析 url 查询字符串。
 *
 * 兼容以 `?` 开头的查询字符串,因此你可以直接传入 `location.search` 的值。
 *
 * @param query 查询字符串
 * @param options 选项
 * @returns 返回 url 查询参数
 * @example
 * ```typescript
 * parseUrlQueryString('x=1&y=z') // => { x: '1', y: 'z' }
 * ```
 */
export function parseUrlQueryString<
  T extends Record<string, string> = Record<string, string>
>(query: string, options?: CreateUrlQueryStringOptions): T {
  if (!query) return {} as any
  const pairSeparator = options?.pairSeparator ?? '='
  const partSeparator = options?.partSeparator ?? '&'
  const parameters: T = {} as any
  query = query.charAt(0) === '?' ? query.substring(1) : query
  for (const pair of query.split(partSeparator)) {
    const [key, value] = pair.split(pairSeparator)
    Iif (!key) continue
    const decodedKey = decodeURIComponent(key)
    const decodedValue = value ? decodeURIComponent(value) : ''
    ;(parameters as any)[decodedKey] = decodedValue
  }
  return parameters
}