JSFiddle - React, Tailwind, and code Playground
JavaScript
String.prototype.addQuery = function (obj) {
return this + Object.keys(obj).reduce(function (p, e, i) {
return p + (i == 0 ? "?" : "&") +
(Array.isArray(obj[e]) ? obj[e].reduce(function (str, f, j) {
return str + e + "=" + encodeURIComponent(f) + (j != obj[e].length - 1 ? "&" : "")
}, "") : e + "=" + encodeURIComponent(obj[e]));
}, "");
}
function myFunction() {
const url = "https://sampleUrl";
const query = {
query1: ["value1A", "value1B", "value1C"],
query2: "value2A, value2B",
query3: "value3A/value3B",
};
const endpoint = url.addQuery(query);
console.log(endpoint);
}
myFunction();