In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:
Original URL:
This was my own attempt, but I'll use the answer by annakata as it seems much cleaner:
function AddUrlParameter(sourceUrl, parameterName, parameterValue, replaceDuplicates)
{
if ((sourceUrl == null) || (sourceUrl.length == 0)) sourceUrl = document.location.href;
var urlParts = sourceUrl.split("?");
var newQueryString = "";
if (urlParts.length > 1)
{
var parameters = urlParts[1].split("&");
for (var i=0; (i < parameters.length); i++)
{
var parameterParts = parameters[i].split("=");
if (!(replaceDuplicates && parameterParts[0] == parameterName))
{
if (newQueryString == "")
newQueryString = "?";
else
newQueryString += "&";
newQueryString += parameterParts[0] + "=" + parameterParts[1];
}
}
}
if (newQueryString == "")
newQueryString = "?";
else
newQueryString += "&";
newQueryString += parameterName + "=" + parameterValue;
return urlParts[0] + newQueryString;
}
Also, I found this jQuery plugin from another post on stackoverflow, and if you need more flexibility you could use that: http://plugins.jquery.com/project/query-object
I would think the code would be (haven't tested):
return $.query.parse(sourceUrl).set(parameterName, parameterValue).toString();
It handles such URL's:
?
at the end, but at the same time doesn't have any parametersIt doesn't handles such URL's:
Works in:
function appendQueryParameter(url, name, value) {
if (url.length === 0) {
return;
}
let rawURL = url;
// URL with `?` at the end and without query parameters
// leads to incorrect result.
if (rawURL.charAt(rawURL.length - 1) === "?") {
rawURL = rawURL.slice(0, rawURL.length - 1);
}
const parsedURL = new URL(rawURL);
let parameters = parsedURL.search;
parameters += (parameters.length === 0) ? "?" : "&";
parameters = (parameters + name + "=" + value);
return (parsedURL.origin + parsedURL.pathname + parameters);
}
Version with ES6 template strings.
Works in:
function appendQueryParameter(url, name, value) {
if (url.length === 0) {
return;
}
let rawURL = url;
// URL with `?` at the end and without query parameters
// leads to incorrect result.
if (rawURL.charAt(rawURL.length - 1) === "?") {
rawURL = rawURL.slice(0, rawURL.length - 1);
}
const parsedURL = new URL(rawURL);
let parameters = parsedURL.search;
parameters += (parameters.length === 0) ? "?" : "&";
parameters = `${parameters}${name}=${value}`;
return `${parsedURL.origin}${parsedURL.pathname}${parameters}`;
}
Try
The regular expressions, so slow, thus:
var SetParamUrl = function(_k, _v) {// replace and add new parameters
let arrParams = window.location.search !== '' ? decodeURIComponent(window.location.search.substr(1)).split('&').map(_v => _v.split('=')) : Array();
let index = arrParams.findIndex((_v) => _v[0] === _k);
index = index !== -1 ? index : arrParams.length;
_v === null ? arrParams = arrParams.filter((_v, _i) => _i != index) : arrParams[index] = [_k, _v];
let _search = encodeURIComponent(arrParams.map(_v => _v.join('=')).join('&'));
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + (arrParams.length > 0 ? '?' + _search : '');
// window.location = newurl; //reload
if (history.pushState) { // without reload
window.history.pushState({path:newurl}, null, newurl);
}
};
var GetParamUrl = function(_k) {// get parameter by key
let sPageURL = decodeURIComponent(window.location.search.substr(1)),
sURLVariables = sPageURL.split('&').map(_v => _v.split('='));
let _result = sURLVariables.find(_v => _v[0] === _k);
return _result[1];
};
Example:
// https://some.com/some_path
GetParamUrl('cat');//undefined
SetParamUrl('cat', "strData");// https://some.com/some_path?cat=strData
GetParamUrl('cat');//strData
SetParamUrl('sotr', "strDataSort");// https://some.com/some_path?cat=strData&sotr=strDataSort
GetParamUrl('sotr');//strDataSort
SetParamUrl('cat', "strDataTwo");// https://some.com/some_path?cat=strDataTwo&sotr=strDataSort
GetParamUrl('cat');//strDataTwo
//remove param
SetParamUrl('cat', null);// https://some.com/some_path?sotr=strDataSort
You can use one of these:
Example:
var url = new URL("http://foo.bar/?x=1&y=2");
// If your expected result is "http://foo.bar/?x=1&y=2&x=42"
url.searchParams.append('x', 42);
// If your expected result is "http://foo.bar/?x=42&y=2"
url.searchParams.set('x', 42);
Vianney Bajart's answer is correct; however, URL will only work if you have the complete URL with port, host, path and query:
new URL('http://server/myapp.php?id=10&enabled=true')
And URLSearchParams will only work if you pass only the query string:
new URLSearchParams('?id=10&enabled=true')
If you have an incomplete or relative URL and don't care for the base URL, you can just split by ?
to get the query string and join later like this:
function setUrlParams(url, key, value) {
url = url.split('?');
usp = new URLSearchParams(url[1]);
usp.set(key, value);
url[1] = usp.toString();
return url.join('?');
}
let url = 'myapp.php?id=10';
url = setUrlParams(url, 'enabled', true); // url = 'myapp.php?id=10&enabled=true'
url = setUrlParams(url, 'id', 11); // url = 'myapp.php?id=11&enabled=true'
Not compatible with Internet Explorer.
Following function will help you to add,update and delete parameters to or from URL.
//example1and
var myURL = '/search';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search
//example2
var myURL = '/search?category=mobile';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile
//example3
var myURL = '/search?location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search
//example4
var myURL = '/search?category=mobile&location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile
//example5
var myURL = 'https://example.com/search?location=texas#fragment';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california#fragment
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york#fragment
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search#fragment
Here is the function.
function updateUrl(url,key,value){
if(value!==undefined){
value = encodeURI(value);
}
var hashIndex = url.indexOf("#")|0;
if (hashIndex === -1) hashIndex = url.length|0;
var urls = url.substring(0, hashIndex).split('?');
var baseUrl = urls[0];
var parameters = '';
var outPara = {};
if(urls.length>1){
parameters = urls[1];
}
if(parameters!==''){
parameters = parameters.split('&');
for(k in parameters){
var keyVal = parameters[k];
keyVal = keyVal.split('=');
var ekey = keyVal[0];
var evalue = '';
if(keyVal.length>1){
evalue = keyVal[1];
}
outPara[ekey] = evalue;
}
}
if(value!==undefined){
outPara[key] = value;
}else{
delete outPara[key];
}
parameters = [];
for(var k in outPara){
parameters.push(k + '=' + outPara[k]);
}
var finalUrl = baseUrl;
if(parameters.length>0){
finalUrl += '?' + parameters.join('&');
}
return finalUrl + url.substring(hashIndex);
}