Last active
March 22, 2025 19:35
-
-
Save stemar/6490d35c66b917b2068fb687aa9a125b to your computer and use it in GitHub Desktop.
Encode data into a query string for a GET or POST request, in 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 encodeQueryString(params, isPostRequest) { | |
| var query = new Array(); | |
| for (var key in params) { | |
| if (params.hasOwnProperty(key)) { | |
| var value = params[key]; | |
| if (Object.prototype.toString.call(value) === "[object Array]") { | |
| for (var i = 0, n = value.length; i < n; i++) { | |
| query.push(encodeURIComponent(key + "[]") + "=" + encodeURIComponent(value[i])); | |
| } | |
| } else { | |
| query.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)); | |
| } | |
| } | |
| } | |
| query = query.join("&"); | |
| if (isPostRequest) { | |
| query = query.replaceAll("%20", "+"); | |
| query = decodeURIComponent(query); | |
| } | |
| return query; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.