Skip to content

Instantly share code, notes, and snippets.

@LiuJi-Jim
Created January 20, 2016 08:24
Show Gist options
  • Save LiuJi-Jim/72cc8db7bf5489c57c5e to your computer and use it in GitHub Desktop.
Save LiuJi-Jim/72cc8db7bf5489c57c5e to your computer and use it in GitHub Desktop.
URL parsing with HTMLAnchorElement
const RE_URL_ARRAY = /\[(.*?)\]$/
export function parseQuery(search) {
search = search.replace(/^\?/, '')
let query = {}
search.split('&').forEach(pair => {
let kv = pair.split('=')
let key = kv[0]
let value = kv[1]
if (!value) value = ''
value = decodeURIComponent(value)
let match = key.match(RE_URL_ARRAY)
if (match) {
key = key.replace(RE_URL_ARRAY, '')
let subkey = match[1]
if (subkey) {
let dict = query[key] || (query[key] = {})
dict[subkey] = value
} else {
let array = query[key] || (query[key] = [])
array.push(value)
}
} else {
query[key] = value
}
})
return query
}
const _a = document.createElement('a')
export function parseUrl(url) {
// ftp://user:pass@example.com:8080/root/sub/filename?foo=bar&arr[]=1&arr[]=2&kv[foo]=f&kv[bar]=b&empty=&single#hash
_a.href = url
return {
protocol: _a.protocol,
host: _a.host,
hostname: _a.hostname,
port: _a.port,
username: _a.username,
password: _a.password,
pathname: _a.pathname,
search: _a.search,
query: parseQuery(_a.search),
hash: _a.hash
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment