Skip to content

Instantly share code, notes, and snippets.

@ilatypov
Last active April 4, 2018 22:10
Show Gist options
  • Save ilatypov/93779ccecf79058aa8b5533dc0785641 to your computer and use it in GitHub Desktop.
Save ilatypov/93779ccecf79058aa8b5533dc0785641 to your computer and use it in GitHub Desktop.
// "the pattern will be applied at most n - 1 times,
// the array's length will be no greater than n,
// and the array's last entry will contain all input
// beyond the last matched delimiter"
// java_split("a=b=c", "=", 2) => ["a", "b=c"]
function java_split(s, sep, max_num_elements) {
// "stops when limit entries have been placed into the array"
// "a=b=c".split("=", 2) => ["a", "b"]
var p = s.split(sep, max_num_elements);
var stopped_length = p.reduce((acc, v) => acc + v.length + sep.length, 0);
if (stopped_length <= s.length) {
p[p.length - 1] += (sep + s.substring(stopped_length));
}
return p;
}
// Usage:
// var params = parse_query(window.location.hash.substring(1));
// var value = params["key"];
function parse_query(q) {
// BrunoLM https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
if (q == "") return {};
var qa = q.split('&');
var params = {};
for (var i = 0; i < qa.length; ++i) {
var p = java_split(qa[i], '=', 2);
var name = p[0];
var value;
if (p.length == 1) {
value = "";
} else {
value = decodeURIComponent(p[1].replace(/\+/g, " "));
}
params[name] = value;
}
return params;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment