Last active
January 9, 2025 13:29
-
-
Save bookmebus/f928c078923636cd46be5511d417668e to your computer and use it in GitHub Desktop.
Add or Modify url query string with javascript and JQuery
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
// Not Required Jquery | |
// currentURL = location.protocol + '//' + location.host + location.pathname + location.search + location.hash | |
function ModifyQueryString(url, newKey, newValue){ | |
var params = {} | |
var urlSplits = url.split("?"); | |
var baseURL = urlSplits[0] | |
var queryString = urlSplits[1] | |
if(!queryString) { | |
params[newKey] = newValue | |
var hashSplits = baseURL.split("#") | |
baseURL = hashSplits[0] | |
var hash = hashSplits[1] | |
var result = baseURL + "?" + SerializeParam(params) | |
if(hash) | |
result += "#" + hash | |
return result | |
} | |
var hashSplits = queryString.split("#") | |
queryString = hashSplits[0] | |
var hash = hashSplits[1] | |
if (queryString) { | |
queries = queryString.split("&"); | |
for (var i=0; i<queries.length; i++){ | |
var keyValues = queries[i].split('=') | |
params[keyValues[0]] = keyValues[1] | |
} | |
} | |
params[newKey] = newValue | |
// require jquery | |
var result = baseURL + "?" + SerializeParam(params) | |
if(hash) | |
result += "#" + hash | |
return result | |
} | |
function SerializeParam(params) { | |
if(typeof $ !== "undefined" && typeof $.param !== "undefined" ) | |
return $.param(params) | |
var queryString = "" | |
for(prop in params) { | |
queryString += prop + "&" + encodeURIComponent(params[prop]) | |
} | |
return queryString | |
} | |
// spec for unit test. | |
/* | |
# url without hash and query string | |
var result = ModifyQueryString("http://www.bookmebus.com", "id", "order-123") | |
expect(result).to eq "http://www.bookmebus.com?id=order-123" | |
# url with hash and no query string | |
var result = ModifyQueryString("http://www.bookmebus.com#popular", "id", "order-123") | |
expect(result).to eq "http://www.bookmebus.com?id=order-123#popular" | |
# url with query string no hash | |
var result = ModifyQueryString("http://www.bookmebus.com?id=order-123&p=pipay", "p", "abapay") | |
expect(result).to eq "http://www.bookmebus.com?id=order-123&p=abapay" | |
# url with query string no hash | |
var result = ModifyQueryString("http://www.bookmebus.com?id=order-123&p=pipay#payment-local", "p", "abapay") | |
expect(result).to eq "http://www.bookmebus.com?id=order-123&p=abapay#payment-local" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment