JSFiddle - React, Tailwind, and code Playground
by tonytlwu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
JavaScript
function addQueryToUrl(url, query) {
if (typeof query === 'undefined') {
return url;
}
var pieces = url.split('?');
url = pieces.shift();
pieces = _.compact(pieces).map(function (piece) {
// Clean up empty queries
return _.compact(piece.split('&')).join('&');
});
if (typeof query === 'object') {
// Parse query object into an array of key=value strings
Object.keys(query).forEach(function (key) {
pieces.push(key + '=' + encodeURIComponent(query[key]));
});
} else {
pieces.push(query);
}
return [url, pieces.join('&')].join('?');
}
console.log(addQueryToUrl("example1.org"));
console.log(addQueryToUrl("example1.org?bar"));
console.log(addQueryToUrl("example1.org", "bar"));
console.log(addQueryToUrl("example1.org?", { bar: undefined }));
console.log(addQueryToUrl("example2.org?foo", "bar&baz"));
console.log(addQueryToUrl("example2.org?foo", { bar: 1, baz: 2 }));
console.log(addQueryToUrl("example3.org?foo&bar&", { baz: [1, 2, 3] })); // Not supported