JSFiddle - React, Tailwind, and code Playground
by lbstr
HTML
<ul id="log">
</ul>
JavaScript
var addQSP = function(url, key, value, addToBeginning) {
var keyValPair = key + "=" + value,
newUrl, parts, exisingQS, qs1, qs2;
if (url && url.length) {
parts = url.split('?');
existingQS = parts[1] || '';
if (addToBeginning) {
qs1 = keyValPair;
qs2 = existingQS.length ? "&" + existingQS : '';
}
else {
qs1 = existingQS.length ? existingQS : '';
qs2 = "&" + keyValPair;
}
newUrl = parts[0] + "?" + qs1 + qs2;
}
else {
newUrl = url;
}
return newUrl;
};
var log = function(msg){
console.log(msg);
var log = document.getElementById('log');
var msgEl = document.createElement('li');
msgEl.innerHTML = msg;
log.appendChild(msgEl);
};
log(addQSP("http://localhost/foo?a=b", "jp", "1", true));
log(addQSP(null, "jp", "1", true));
log(addQSP("http://localhost/foo", "jp", "1", true));
log(addQSP("http://localhost/foo?a=b&c=d", "jp", "1", true));
log(addQSP("http://localhost/foo?a=b", "jp", "1"));
log(addQSP(null, "jp", "1"));
log(addQSP("http://localhost/foo", "jp", "1"));
log(addQSP("http://localhost/foo?a=b&c=d", "jp", "1"));