Last active
March 21, 2025 14:50
-
-
Save stemar/32dec51a21f677662a9d8c6e8c69b645 to your computer and use it in GitHub Desktop.
PHP's http_build_query equivalent with RFC3986 for JavaScript ES5
This file contains hidden or 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 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Default is RFC_3986 (%20 for space), unlike PHP's default of RFC_1738 (+ for space).