-
-
Save jgornick/8ceba659dcd096be2abc to your computer and use it in GitHub Desktop.
JS: toQueryParams
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
function toQueryParams(string, separator) { | |
string = String(string); | |
var match = string.split('?'), object = {}; | |
// if ? (question mark) is present and there is no query after it | |
if (match.length > 1 && !match[1]) return object; | |
// since we split on the ?, let's merge back everything after | |
// the question mark as there could be a url with a parameter | |
// containing another url with query. | |
match = match.slice(1).join('?'); | |
// bail if empty string | |
if (!match) return object; | |
var pair, key, value, index, i = 0, | |
pairs = match.split(separator || '&'), length = pairs.length; | |
// iterate over key-value pairs | |
for ( ; i < length; i++) { | |
value = undefined; | |
index = (pair = pairs[i]).indexOf('='); | |
if (!pair || index == 0) continue; | |
// grab the query before the # (hash) and\or spaces | |
(pair = pair.split('#')) && (pair = pair[0].split(' ')[0]); | |
if (index != -1) { | |
key = decodeURIComponent(pair.slice(0, index)); | |
value = pair.slice(index + 1); | |
if (value) value = decodeURIComponent(value); | |
} else key = pair; | |
if (object[key]) { | |
if (Object.prototype.toString.call(object[key]) !== '[object Array]') object[key] = [object[key]]; | |
object[key].push(value); | |
} | |
else object[key] = value; | |
} | |
return object; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment