Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active March 21, 2025 14:50
Show Gist options
  • Save stemar/32dec51a21f677662a9d8c6e8c69b645 to your computer and use it in GitHub Desktop.
Save stemar/32dec51a21f677662a9d8c6e8c69b645 to your computer and use it in GitHub Desktop.
PHP's http_build_query equivalent with RFC3986 for JavaScript ES5
function http_build_query(data, numeric_prefix, arg_separator, encoding_type_RFC1738) {
var i = 0, j = 0, encoded_key, encoded_val, query = [];
if (typeof arg_separator === "undefined") {
arg_separator = "&";
}
for (var key in data) {
if (data.hasOwnProperty(key)) {
var value = data[key];
if (Object.prototype.toString.call(value) === "[object Array]") {
for (var i = 0; i < value.length; i++) {
encoded_key = encodeURIComponent(key + "[]");
encoded_val = encodeURIComponent(value[i].toString());
if (numeric_prefix && !isNaN(key)) {
encoded_key = numeric_prefix + j;
j++;
}
query.push(encoded_key + "=" + encoded_val);
}
} else {
encoded_key = encodeURIComponent(key);
encoded_val = encodeURIComponent(value.toString());
if (numeric_prefix && !isNaN(key)) {
encoded_key = numeric_prefix + j;
j++;
}
query.push(encoded_key + "=" + encoded_val);
}
}
}
query = query.join(arg_separator);
if (encoding_type_RFC1738) {
query = decodeURIComponent(query);
}
return query;
}
@stemar
Copy link
Author

stemar commented Feb 8, 2025

Default is RFC_3986 (%20 for space), unlike PHP's default of RFC_1738 (+ for space).

http_build_query({a: 'ace', b: 'boss of ace'});
a=ace&b=boss%20of%20ace
http_build_query({a: 'ace', b: 'boss of ace'}, '', '&', true);
a=ace&b=boss+of+ace
http_build_query({a: 'ace', b: 'boss of ace', 0: 'boom'}, '', '&amp;', 1);
0=boom&amp;a=ace&amp;b=boss+of+ace
http_build_query({a: 'ace', b: 'boss of ace', 0: 'boom'}, 'var_');
var_0=boom&a=ace&b=boss%20of%20ace
http_build_query({a: 'ace', b: 'boss of ace', ids: [12,34,56], 0: 'boom', 1: 'pow'}, 'var_', '&amp;', 1);
var_0=boom&amp;var_1=pow&amp;a=ace&amp;b=boss+of+ace&amp;ids%5B%5D=12&amp;ids%5B%5D=34&amp;ids%5B%5D=56
http_build_query({a: 'ace', b: 'boss of ace', ids: [12,34,56], 0: 'boom', 1: 'pow'}, 'var_');
var_0=boom&var_1=pow&a=ace&b=boss%20of%20ace&ids%5B%5D=12&ids%5B%5D=34&ids%5B%5D=56
http_build_query({a: 'ace', b: 'boss of ace', ids: [12,34,56], 0: 'boom', 1: 'pow'});
0=boom&1=pow&a=ace&b=boss%20of%20ace&ids%5B%5D=12&ids%5B%5D=34&ids%5B%5D=56
decodeURIComponent(http_build_query({a: 'ace', b: 'boss of ace', ids: [12,34,56], 0: 'boom', 1: 'pow'}));
0=boom&1=pow&a=ace&b=boss of ace&ids[]=12&ids[]=34&ids[]=56
decodeURIComponent(http_build_query({a: 'ace', b: 'boss of ace', ids: [12,34,56], 0: 'boom', 1: 'pow'}, '', '&', 1));
0=boom&1=pow&a=ace&b=boss+of+ace&ids[]=12&ids[]=34&ids[]=56

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment