Last active
November 20, 2017 19:45
-
-
Save alexsasharegan/ea5de3bd3372c2cc4ccccdd2173052d5 to your computer and use it in GitHub Desktop.
Encode and decode urls.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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