Skip to content

Instantly share code, notes, and snippets.

@Yaffle
Last active December 2, 2015 11:56
Show Gist options
  • Save Yaffle/11390013 to your computer and use it in GitHub Desktop.
Save Yaffle/11390013 to your computer and use it in GitHub Desktop.
http://url.spec.whatwg.org/ - thanks to Anne van Kesteren for the spec
"use strict";
function URLSearchParams(query) {
var data = [];
query = query.toString();
query = query.replace(/\+/g, " ");
var strings = query.split("&");
var l = strings.length;
var i = 0;
while (i < l) {
var s = strings[i];
if (s !== "") {
var j = s.indexOf("=");
var name = s;
var value = "";
if (j !== -1) {
name = s.slice(0, j);
value = s.slice(j + 1);
}
name = decodeURIComponent(name);
value = decodeURIComponent(value);
data.push(name);
data.push(value);
}
i += 1;
}
this.data = data;
}
URLSearchParams.prototype.get = function (name) {
name = name.toString();
var data = this.data;
var l = data.length;
var i = 0;
while (i < l) {
if (data[i] === name) {
return data[i + 1];
}
i += 2;
}
return undefined;
};
URLSearchParams.prototype.getAll = function (name) {
name = name.toString();
var x = [];
var data = this.data;
var l = data.length;
var i = 0;
while (i < l) {
if (data[i] === name) {
x.push(data[i + 1]);
}
i += 2;
}
return x;
};
URLSearchParams.prototype.set = function (name, value) {
name = name.toString();
value = value.toString();
var data = this.data;
var l = data.length;
var i = 0;
while (i < l) {
if (data[i] === name) {
data[i + 1] = value;
return;
}
i += 2;
}
data.push(name);
data.push(value);
};
URLSearchParams.prototype.append = function (name, value) {
name = name.toString();
value = value.toString();
var data = this.data;
data.push(name);
data.push(value);
};
URLSearchParams.prototype.has = function (name) {
name = name.toString();
var data = this.data;
var l = data.length;
var i = 0;
while (i < l) {
if (data[i] === name) {
return true;
}
i += 2;
}
return false;
};
URLSearchParams.prototype["delete"] = function (name) {
name = name.toString();
var data = this.data;
var l = data.length;
var i = 0;
var k = -1;
while (i < l) {
if (data[i] !== name) {
k += 1;
data[k] = data[i];
k += 1;
data[k] = data[i + 1];
}
i += 2;
}
data.length = k + 1;
};
URLSearchParams.prototype.toString = function () {
var output = "";
var data = this.data;
var l = data.length;
var i = 0;
while (i < l) {
output += (encodeURIComponent(data[i]));
if (data[i + 1] !== "") {
output += ("=");
output += (encodeURIComponent(data[i + 1]));
}
output += "&";
i += 2;
}
return output;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment