Created
August 10, 2018 03:02
-
-
Save channainfo/0ecfbf9cdaa692611e1a616e1235219a to your computer and use it in GitHub Desktop.
Add or modify current url query string with new values in JQuery javascript
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
// Luckily Jquery not required. | |
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