Skip to content

Instantly share code, notes, and snippets.

@alexsasharegan
Last active November 20, 2017 19:45
Show Gist options
  • Save alexsasharegan/ea5de3bd3372c2cc4ccccdd2173052d5 to your computer and use it in GitHub Desktop.
Save alexsasharegan/ea5de3bd3372c2cc4ccccdd2173052d5 to your computer and use it in GitHub Desktop.
Encode and decode urls.
/**
* RegExpURL matches URLs containing a query string.
* - [0] full match
* - [1] base url
* - [2] query string
* - [3] hash (without #)
*/
const RegExpURL = /^(.*)\?([^#]*)(?:#(.*))?$/
/**
* RegExpListKey matches a URL key/value pair that uses array syntax (`key[]=value`).
* - [0] full match
* - [1] key
* - [2] index
* - [3] value
*/
const RegExpListKey = /^(.+)\[(\d*)]=(.+)$/
export function Decode(queryString: string) {
let decoded: object = Object.create(null),
matches: string[] | null = null,
k = "",
v = ""
// Test for a full URL. If match, extract query.
if (RegExpURL.test(queryString) && (matches = RegExpURL.exec(queryString)) != null) {
queryString = matches[2]
matches = null
}
for (const kvPair of queryString.split("&")) {
// Test for list key items (`key[]=value`).
if (RegExpListKey.test(kvPair) && (matches = RegExpListKey.exec(kvPair)) != null) {
k = decodeURIComponent(matches[1])
v = decodeURIComponent(matches[3])
matches = null
if (!Array.isArray(decoded[k])) {
decoded[k] = []
}
decoded[k].push(v)
continue
}
;[k, v] = kvPair.split("=")
if (!k) {
continue
}
decoded[decodeURIComponent(k)] = decodeURIComponent(v)
}
return decoded
}
export function Encode(data: object) {
let encoded = []
for (const k of Object.getOwnPropertyNames(data)) {
if (typeof data[k] == "function" || data[k] === undefined) {
continue
}
if (Array.isArray(data[k])) {
for (const v of data[k]) {
encoded.push(encodeURIComponent(k) + "[]=" + encodeURIComponent(v))
}
continue
}
encoded.push(encodeURIComponent(k) + "=" + encodeURIComponent(data[k]))
}
return encoded.join("&")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment