Skip to content

Instantly share code, notes, and snippets.

@Fog3211
Last active February 15, 2023 16:03
Show Gist options
  • Save Fog3211/b1f60ba92c2770718c6473cd709724ef to your computer and use it in GitHub Desktop.
Save Fog3211/b1f60ba92c2770718c6473cd709724ef to your computer and use it in GitHub Desktop.
[parse-url] 解析url参数 #Typescript
export const parseUrl = (url: string) => {
if (!url) return {}
const searchUrl: string = url.indexOf('?') ? url.match(/.+\?(.+)/)![1] : url
const searchParams = searchUrl.split('&')
const result: Record<string, string | string[]> = {}
searchParams.forEach(item => {
const [key, value] = item.split('=') as [string, string]
if (item.indexOf('=') === -1) {
result[key] = ''
} else {
const decodedValue = decodeURIComponent(value)
result[key] = result[key] === undefined ? decodedValue : [...result[key], decodedValue]
}
})
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment