Related
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:
http://server/myapp.php?id=10
Resulting URL:
http://server/myapp.php?id=10&enabled=true
Looking for a JavaScript function which parses the URL looking at each parameter, then adds the new parameter or updates the value if one already exists.
You can use one of these:
https://developer.mozilla.org/en-US/docs/Web/API/URL
https://developer.mozilla.org/en/docs/Web/API/URLSearchParams
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);
You can use url.href or url.toString() to get the full URL
A basic implementation which you'll need to adapt would look something like this:
function insertParam(key, value) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);
// kvp looks like ['key1=value1', 'key2=value2', ...]
var kvp = document.location.search.substr(1).split('&');
let i=0;
for(; i<kvp.length; i++){
if (kvp[i].startsWith(key + '=')) {
let pair = kvp[i].split('=');
pair[1] = value;
kvp[i] = pair.join('=');
break;
}
}
if(i >= kvp.length){
kvp[kvp.length] = [key,value].join('=');
}
// can return this or...
let params = kvp.join('&');
// reload page with new params
document.location.search = params;
}
This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match
the slow regex method I benchmarked against for completions sake (approx +150% slower)
function insertParam2(key,value)
{
key = encodeURIComponent(key); value = encodeURIComponent(value);
var s = document.location.search;
var kvp = key+"="+value;
var r = new RegExp("(&|\\?)"+key+"=[^\&]*");
s = s.replace(r,"$1"+kvp);
if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};
//again, do what you will here
document.location.search = s;
}
You can use URLSearchParams
const urlParams = new URLSearchParams(window.location.search);
urlParams.set('order', 'date');
window.location.search = urlParams;
.set first agrument is the key, the second one is the value.
Note: this is not supported in any version of Internet Explorer (but is supported in Edge)
This is very simple solution. Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to end, so you can get latest value in your back-end code.
function addParameterToURL(param){
_url = location.href;
_url += (_url.split('?')[1] ? '&':'?') + param;
return _url;
}
Thank you all for your contribution. I used annakata code and modified to also include the case where there is no query string in the url at all.
Hope this would help.
function insertParam(key, value) {
key = escape(key); value = escape(value);
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
document.location.search = '?' + key + '=' + value;
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}
}
Here's a vastly simplified version, making tradeoffs for legibility and fewer lines of code instead of micro-optimized performance (and we're talking about a few miliseconds difference, realistically... due to the nature of this (operating on the current document's location), this will most likely be ran once on a page).
/**
* Add a URL parameter (or changing it if it already exists)
* #param {search} string this is typically document.location.search
* #param {key} string the key to set
* #param {val} string value
*/
var addUrlParam = function(search, key, val){
var newParam = key + '=' + val,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (search) {
// Try to replace an existance instance
params = search.replace(new RegExp('([?&])' + key + '[^&]*'), '$1' + newParam);
// If nothing was replaced, then add the new param to the end
if (params === search) {
params += '&' + newParam;
}
}
return params;
};
You would then use this like so:
document.location.pathname + addUrlParam(document.location.search, 'foo', 'bar');
There is a built-in function inside URL class that you can use it for easy dealing with query string key/value params:
const url = new URL(window.location.href);
// url.searchParams has several function, we just use `set` function
// to set a value, if you just want to append without replacing value
// let use `append` function
url.searchParams.set('key', 'value');
console.log(url.search) // <== '?key=value'
// if window.location.href has already some qs params this `set` function
// modify or append key/value in it
For more information about searchParams functions.
URL is not supported in IE, check compatibility
/**
* Add a URL parameter
* #param {string} url
* #param {string} param the key to set
* #param {string} value
*/
var addParam = function(url, param, value) {
param = encodeURIComponent(param);
var a = document.createElement('a');
param += (value ? "=" + encodeURIComponent(value) : "");
a.href = url;
a.search += (a.search ? "&" : "") + param;
return a.href;
}
/**
* Add a URL parameter (or modify if already exists)
* #param {string} url
* #param {string} param the key to set
* #param {string} value
*/
var addOrReplaceParam = function(url, param, value) {
param = encodeURIComponent(param);
var r = "([&?]|&)" + param + "\\b(?:=(?:[^&#]*))*";
var a = document.createElement('a');
var regex = new RegExp(r);
var str = param + (value ? "=" + encodeURIComponent(value) : "");
a.href = url;
var q = a.search.replace(regex, "$1"+str);
if (q === a.search) {
a.search += (a.search ? "&" : "") + str;
} else {
a.search = q;
}
return a.href;
}
url = "http://www.example.com#hashme";
newurl = addParam(url, "ciao", "1");
alert(newurl);
And please note that parameters should be encoded before being appended in query string.
http://jsfiddle.net/48z7z4kx/
I have a 'class' that does this and here it is:
function QS(){
this.qs = {};
var s = location.search.replace( /^\?|#.*$/g, '' );
if( s ) {
var qsParts = s.split('&');
var i, nv;
for (i = 0; i < qsParts.length; i++) {
nv = qsParts[i].split('=');
this.qs[nv[0]] = nv[1];
}
}
}
QS.prototype.add = function( name, value ) {
if( arguments.length == 1 && arguments[0].constructor == Object ) {
this.addMany( arguments[0] );
return;
}
this.qs[name] = value;
}
QS.prototype.addMany = function( newValues ) {
for( nv in newValues ) {
this.qs[nv] = newValues[nv];
}
}
QS.prototype.remove = function( name ) {
if( arguments.length == 1 && arguments[0].constructor == Array ) {
this.removeMany( arguments[0] );
return;
}
delete this.qs[name];
}
QS.prototype.removeMany = function( deleteNames ) {
var i;
for( i = 0; i < deleteNames.length; i++ ) {
delete this.qs[deleteNames[i]];
}
}
QS.prototype.getQueryString = function() {
var nv, q = [];
for( nv in this.qs ) {
q[q.length] = nv+'='+this.qs[nv];
}
return q.join( '&' );
}
QS.prototype.toString = QS.prototype.getQueryString;
//examples
//instantiation
var qs = new QS;
alert( qs );
//add a sinle name/value
qs.add( 'new', 'true' );
alert( qs );
//add multiple key/values
qs.add( { x: 'X', y: 'Y' } );
alert( qs );
//remove single key
qs.remove( 'new' )
alert( qs );
//remove multiple keys
qs.remove( ['x', 'bogus'] )
alert( qs );
I have overridden the toString method so there is no need to call QS::getQueryString, you can use QS::toString or, as I have done in the examples just rely on the object being coerced into a string.
If you have a string with url that you want to decorate with a param, you could try this oneliner:
urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';
This means that ? will be the prefix of the parameter, but if you already have ? in urlstring, than & will be the prefix.
I would also recommend to do encodeURI( paramvariable ) if you didn't hardcoded parameter, but it is inside a paramvariable; or if you have funny characters in it.
See javascript URL Encoding for usage of the encodeURI function.
This is a simple way to add a query parameter:
const query = new URLSearchParams(window.location.search);
query.append("enabled", "true");
And that is it more here.
Please note the support specs.
This solution updates the window's current URL with updated search parameters without actually reloading the page. This approach is useful in a PWA/SPA context.
function setURLSearchParam(key, value) {
const url = new URL(window.location.href);
url.searchParams.set(key, value);
window.history.pushState({ path: url.href }, '', url.href);
}
Sometimes we see ? at the end URL, I found some solutions which generate results as file.php?&foo=bar. I came up with my own solution to work perfectly as I want!
location.origin + location.pathname + location.search + (location.search=='' ? '?' : '&') + 'lang=ar'
Note: location.origin doesn't work in IE, here is its fix.
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);
}
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();
Check out https://github.com/derek-watson/jsUri
Uri and query string manipulation in javascript.
This project incorporates the excellent parseUri regular expression library by Steven Levithan. You can safely parse URLs of all shapes and sizes, however invalid or hideous.
Adding to #Vianney's Answer https://stackoverflow.com/a/44160941/6609678
We can import the Built-in URL module in node as follows
const { URL } = require('url');
Example:
Terminal $ node
> const { URL } = require('url');
undefined
> let url = new URL('', 'http://localhost:1989/v3/orders');
undefined
> url.href
'http://localhost:1989/v3/orders'
> let fetchAll=true, timePeriod = 30, b2b=false;
undefined
> url.href
'http://localhost:1989/v3/orders'
> url.searchParams.append('fetchAll', fetchAll);
undefined
> url.searchParams.append('timePeriod', timePeriod);
undefined
> url.searchParams.append('b2b', b2b);
undefined
> url.href
'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
> url.toString()
'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
Useful Links:
https://developer.mozilla.org/en-US/docs/Web/API/URL
https://developer.mozilla.org/en/docs/Web/API/URLSearchParams
Try this.
// uses the URL class
function setParam(key, value) {
let url = new URL(window.document.location);
let params = new URLSearchParams(url.search.slice(1));
if (params.has(key)) {
params.set(key, value);
}else {
params.append(key, value);
}
}
It handles such URL's:
empty
doesn't have any parameters
already have some parameters
have ? at the end, but at the same time doesn't have any parameters
It doesn't handles such URL's:
with fragment identifier (i.e. hash, #)
if URL already have required query parameter (then there will be duplicate)
Works in:
Chrome 32+
Firefox 26+
Safari 7.1+
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:
Chrome 41+
Firefox 32+
Safari 9.1+
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}`;
}
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.
The following:
Merges duplicate query string params
Works with absolute and relative URLs
Works in the browser and node
/**
* Adds query params to existing URLs (inc merging duplicates)
* #param {string} url - src URL to modify
* #param {object} params - key/value object of params to add
* #returns {string} modified URL
*/
function addQueryParamsToUrl(url, params) {
// if URL is relative, we'll need to add a fake base
var fakeBase = !url.startsWith('http') ? 'http://fake-base.com' : undefined;
var modifiedUrl = new URL(url || '', fakeBase);
// add/update params
Object.keys(params).forEach(function(key) {
if (modifiedUrl.searchParams.has(key)) {
modifiedUrl.searchParams.set(key, params[key]);
}
else {
modifiedUrl.searchParams.append(key, params[key]);
}
});
// return as string (remove fake base if present)
return modifiedUrl.toString().replace(fakeBase, '');
}
Examples:
// returns /guides?tag=api
addQueryParamsToUrl('/guides?tag=hardware', { tag:'api' })
// returns https://orcascan.com/guides?tag=api
addQueryParamsToUrl('https://orcascan.com/guides?tag=hardware', { tag: 'api' })
I like the answer of Mehmet Fatih Yıldız even he did not answer the whole question.
In the same line as his answer, I use this code:
"Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to the end"
/** add a parameter at the end of the URL. Manage '?'/'&', but not the existing parameters.
* does escape the value (but not the key)
*/
function addParameterToURL(_url,_key,_value){
var param = _key+'='+escape(_value);
var sep = '&';
if (_url.indexOf('?') < 0) {
sep = '?';
} else {
var lastChar=_url.slice(-1);
if (lastChar == '&') sep='';
if (lastChar == '?') sep='';
}
_url += sep + param;
return _url;
}
and the tester:
/*
function addParameterToURL_TESTER_sub(_url,key,value){
//log(_url);
log(addParameterToURL(_url,key,value));
}
function addParameterToURL_TESTER(){
log('-------------------');
var _url ='www.google.com';
addParameterToURL_TESTER_sub(_url,'key','value');
addParameterToURL_TESTER_sub(_url,'key','Text Value');
_url ='www.google.com?';
addParameterToURL_TESTER_sub(_url,'key','value');
_url ='www.google.com?A=B';
addParameterToURL_TESTER_sub(_url,'key','value');
_url ='www.google.com?A=B&';
addParameterToURL_TESTER_sub(_url,'key','value');
_url ='www.google.com?A=1&B=2';
addParameterToURL_TESTER_sub(_url,'key','value');
}//*/
I would go with this small but complete library to handle urls in js:
https://github.com/Mikhus/jsurl
This is what I use when it comes to some basic url param additions or updates on the server-side like Node.js.
CoffeScript:
###
#method addUrlParam Adds parameter to a given url. If the parameter already exists in the url is being replaced.
#param {string} url
#param {string} key Parameter's key
#param {string} value Parameter's value
#returns {string} new url containing the parameter
###
addUrlParam = (url, key, value) ->
newParam = key+"="+value
result = url.replace(new RegExp('(&|\\?)' + key + '=[^\&|#]*'), '$1' + newParam)
if result is url
result = if url.indexOf('?') != -1 then url.split('?')[0] + '?' + newParam + '&' + url.split('?')[1]
else if url.indexOf('#') != -1 then url.split('#')[0] + '?' + newParam + '#' + url.split('#')[1]
else url + '?' + newParam
return result
JavaScript:
function addUrlParam(url, key, value) {
var newParam = key+"="+value;
var result = url.replace(new RegExp("(&|\\?)"+key+"=[^\&|#]*"), '$1' + newParam);
if (result === url) {
result = (url.indexOf("?") != -1 ? url.split("?")[0]+"?"+newParam+"&"+url.split("?")[1]
: (url.indexOf("#") != -1 ? url.split("#")[0]+"?"+newParam+"#"+ url.split("#")[1]
: url+'?'+newParam));
}
return result;
}
var url = "http://www.example.com?foo=bar&ciao=3&doom=5#hashme";
result1.innerHTML = addUrlParam(url, "ciao", "1");
<p id="result1"></p>
Easiest solution, works if you have already a tag or not, and removes it automatically so it wont keep adding equal tags, have fun
function changeURL(tag)
{
if(window.location.href.indexOf("?") > -1) {
if(window.location.href.indexOf("&"+tag) > -1){
var url = window.location.href.replace("&"+tag,"")+"&"+tag;
}
else
{
var url = window.location.href+"&"+tag;
}
}else{
if(window.location.href.indexOf("?"+tag) > -1){
var url = window.location.href.replace("?"+tag,"")+"?"+tag;
}
else
{
var url = window.location.href+"?"+tag;
}
}
window.location = url;
}
THEN
changeURL("i=updated");
const params = new URLSearchParams(window.location.search);
params.delete(key)
window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
If you're messing around with urls in links or somewhere else, you may have to take the hash into account as well. Here's a fairly simple to understand solution. Probably not the FASTEST since it uses a regex... but in 99.999% of cases, the difference really doesn't matter!
function addQueryParam( url, key, val ){
var parts = url.match(/([^?#]+)(\?[^#]*)?(\#.*)?/);
var url = parts[1];
var qs = parts[2] || '';
var hash = parts[3] || '';
if ( !qs ) {
return url + '?' + key + '=' + encodeURIComponent( val ) + hash;
} else {
var qs_parts = qs.substr(1).split("&");
var i;
for (i=0;i<qs_parts.length;i++) {
var qs_pair = qs_parts[i].split("=");
if ( qs_pair[0] == key ){
qs_parts[ i ] = key + '=' + encodeURIComponent( val );
break;
}
}
if ( i == qs_parts.length ){
qs_parts.push( key + '=' + encodeURIComponent( val ) );
}
return url + '?' + qs_parts.join('&') + hash;
}
}
I am adding my solution because it supports relative urls in addition to absolute urls. It is otherwise the same as the top answer which also uses Web API.
/**
* updates a relative or absolute
* by setting the search query with
* the passed key and value.
*/
export const setQueryParam = (url, key, value) => {
const dummyBaseUrl = 'https://dummy-base-url.com';
const result = new URL(url, dummyBaseUrl);
result.searchParams.set(key, value);
return result.toString().replace(dummyBaseUrl, '');
};
And some jest tests:
// some jest tests
describe('setQueryParams', () => {
it('sets param on relative url with base path', () => {
// act
const actual = setQueryParam(
'/', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('/?ref=some-value');
});
it('sets param on relative url with no path', () => {
// act
const actual = setQueryParam(
'', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('/?ref=some-value');
});
it('sets param on relative url with some path', () => {
// act
const actual = setQueryParam(
'/some-path', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('/some-path?ref=some-value');
});
it('overwrites existing param', () => {
// act
const actual = setQueryParam(
'/?ref=prev-value', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('/?ref=some-value');
});
it('sets param while another param exists', () => {
// act
const actual = setQueryParam(
'/?other-param=other-value', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('/?other-param=other-value&ref=some-value');
});
it('honors existing base url', () => {
// act
const actual = setQueryParam(
'https://base.com', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('https://base.com/?ref=some-value');
});
it('honors existing base url with some path', () => {
// act
const actual = setQueryParam(
'https://base.com/some-path', 'ref', 'some-value',
);
// assert
expect(actual).toEqual('https://base.com/some-path?ref=some-value');
});
});
Ok here I compare Two functions, one made by myself (regExp) and another one made by (annakata).
Split array:
function insertParam(key, value)
{
key = escape(key); value = escape(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
return "&"+kvp.join('&');
}
Regexp method:
function addParameter(param, value)
{
var regexp = new RegExp("(\\?|\\&)" + param + "\\=([^\\&]*)(\\&|$)");
if (regexp.test(document.location.search))
return (document.location.search.toString().replace(regexp, function(a, b, c, d)
{
return (b + param + "=" + value + d);
}));
else
return document.location.search+ param + "=" + value;
}
Testing case:
time1=(new Date).getTime();
for (var i=0;i<10000;i++)
{
addParameter("test","test");
}
time2=(new Date).getTime();
for (var i=0;i<10000;i++)
{
insertParam("test","test");
}
time3=(new Date).getTime();
console.log((time2-time1)+" "+(time3-time2));
It seems that even with simplest solution (when regexp use only test and do not enter .replace function) it is still slower than spliting... Well. Regexp is kinda slow but... uhh...
Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:
window.history.replaceState('object or string', 'Title', 'page.html' + editParams('enable', 'true'));
// background functions below:
// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
key = encodeURI(key);
var params = getSearchParameters();
if (Object.keys(params).length === 0) {
if (value !== false)
return '?' + key + '=' + encodeURI(value);
else
return '';
}
if (value !== false)
params[key] = encodeURI(value);
else
delete params[key];
if (Object.keys(params).length === 0)
return '';
return '?' + $.map(params, function (value, key) {
return key + '=' + value;
}).join('&');
}
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
Is there better way to delete a parameter from a query string in a URL string in standard JavaScript other than by using a regular expression?
Here's what I've come up with so far which seems to work in my tests, but I don't like to reinvent querystring parsing!
function RemoveParameterFromUrl( url, parameter ) {
if( typeof parameter == "undefined" || parameter == null || parameter == "" ) throw new Error( "parameter is required" );
url = url.replace( new RegExp( "\\b" + parameter + "=[^&;]+[&;]?", "gi" ), "" ); "$1" );
// remove any leftover crud
url = url.replace( /[&;]$/, "" );
return url;
}
"[&;]?" + parameter + "=[^&;]+"
Seems dangerous because it parameter ‘bar’ would match:
?a=b&foobar=c
Also, it would fail if parameter contained any characters that are special in RegExp, such as ‘.’. And it's not a global regex, so it would only remove one instance of the parameter.
I wouldn't use a simple RegExp for this, I'd parse the parameters in and lose the ones you don't want.
function removeURLParameter(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts = url.split('?');
if (urlparts.length >= 2) {
var prefix = encodeURIComponent(parameter) + '=';
var pars = urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i = pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
}
return url;
}
Modern browsers provide URLSearchParams interface to work with search params. Which has delete method that removes param by name.
if (typeof URLSearchParams !== 'undefined') {
const params = new URLSearchParams('param1=1¶m2=2¶m3=3')
console.log(params.toString())
params.delete('param2')
console.log(params.toString())
} else {
console.log(`Your browser ${navigator.appVersion} does not support URLSearchParams`)
}
You can change the URL with:
window.history.pushState({}, document.title, window.location.pathname);
this way, you can overwrite the URL without the search parameter, I use it to clean the URL after take the GET parameters.
I don't see major issues with a regex solution. But, don't forget to preserve the fragment identifier (text after the #).
Here's my solution:
function RemoveParameterFromUrl(url, parameter) {
return url
.replace(new RegExp('[?&]' + parameter + '=[^&#]*(#.*)?$'), '$1')
.replace(new RegExp('([?&])' + parameter + '=[^&]*&'), '$1');
}
And to bobince's point, yes - you'd need to escape . characters in parameter names.
If it's an instance of URL, use the delete function of searchParams
let url = new URL(location.href);
url.searchParams.delete('page');
Copied from bobince answer, but made it support question marks in the query string, eg
http://www.google.com/search?q=test???+something&aq=f
Is it valid to have more than one question mark in a URL?
function removeUrlParameter(url, parameter) {
var urlParts = url.split('?');
if (urlParts.length >= 2) {
// Get first part, and remove from array
var urlBase = urlParts.shift();
// Join it back up
var queryString = urlParts.join('?');
var prefix = encodeURIComponent(parameter) + '=';
var parts = queryString.split(/[&;]/g);
// Reverse iteration as may be destructive
for (var i = parts.length; i-- > 0; ) {
// Idiom for string.startsWith
if (parts[i].lastIndexOf(prefix, 0) !== -1) {
parts.splice(i, 1);
}
}
url = urlBase + '?' + parts.join('&');
}
return url;
}
Here is what I'm using:
if (location.href.includes('?')) {
history.pushState({}, null, location.href.split('?')[0]);
}
Original URL: http://www.example.com/test/hello?id=123&foo=bar
Destination URL: http://www.example.com/test/hello
Now this answer seems even better! (not fully tested though)
This is a clean version remove query parameter with the URL class for today browsers:
function removeUrlParameter(url, paramKey)
{
var r = new URL(url);
r.searchParams.delete(paramKey);
return r.href;
}
URLSearchParams not supported on old browsers
https://caniuse.com/#feat=urlsearchparams
IE, Edge (below 17) and Safari (below 10.3) do not support URLSearchParams inside URL class.
Polyfills
URLSearchParams only polyfill
https://github.com/WebReflection/url-search-params
Complete Polyfill URL and URLSearchParams to match last WHATWG specifications
https://github.com/lifaon74/url-polyfill
Anyone interested in a regex solution I have put together this function to add/remove/update a querystring parameter. Not supplying a value will remove the parameter, supplying one will add/update the paramter. If no URL is supplied, it will be grabbed from window.location. This solution also takes the url's anchor into consideration.
function UpdateQueryString(key, value, url) {
if (!url) url = window.location.href;
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
hash;
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null)
return url.replace(re, '$1' + key + "=" + value + '$2$3');
else {
hash = url.split('#');
url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
if (typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
}
else {
if (typeof value !== 'undefined' && value !== null) {
var separator = url.indexOf('?') !== -1 ? '&' : '?';
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
else
return url;
}
}
UPDATE
There was a bug when removing the first parameter in the querystring, I have reworked the regex and test to include a fix.
UPDATE 2
#schellmax update to fix situation where hashtag symbol is lost when removing a querystring variable directly before a hashtag
Here a solution that:
uses URLSearchParams (no difficult to understand regex)
updates the URL in the search bar without reload
maintains all other parts of the URL (e.g. hash)
removes superflous ? in query string if the last parameter was removed
function removeParam(paramName) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.delete(paramName);
if (history.replaceState) {
let searchString = searchParams.toString().length > 0 ? '?' + searchParams.toString() : '';
let newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + searchString + window.location.hash;
history.replaceState(null, '', newUrl);
}
}
Note: as pointed out in other answers URLSearchParams is not supported in IE, so use a polyfill.
Assuming you want to remove key=val parameter from URI:
function removeParam(uri) {
return uri.replace(/([&\?]key=val*$|key=val&|[?&]key=val(?=#))/, '');
}
Heres a complete function for adding and removing parameters based on this question and this github gist:
https://gist.github.com/excalq/2961415
var updateQueryStringParam = function (key, value) {
var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
urlQueryString = document.location.search,
newParam = key + '=' + value,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (urlQueryString) {
updateRegex = new RegExp('([\?&])' + key + '[^&]*');
removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');
if( typeof value == 'undefined' || value == null || value == '' ) { // Remove param if value is empty
params = urlQueryString.replace(removeRegex, "$1");
params = params.replace( /[&;]$/, "" );
} else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
params = urlQueryString.replace(updateRegex, "$1" + newParam);
} else { // Otherwise, add it to end of query string
params = urlQueryString + '&' + newParam;
}
}
window.history.replaceState({}, "", baseUrl + params);
};
You can add parameters like this:
updateQueryStringParam( 'myparam', 'true' );
And remove it like this:
updateQueryStringParam( 'myparam', null );
In this thread many said that the regex is probably not the best/stable solution ... so im not 100% sure if this thing has some flaws but as far as i tested it it works pretty fine.
Using jQuery:
function removeParam(key) {
var url = document.location.href;
var params = url.split('?');
if (params.length == 1) return;
url = params[0] + '?';
params = params[1];
params = params.split('&');
$.each(params, function (index, value) {
var v = value.split('=');
if (v[0] != key) url += value + '&';
});
url = url.replace(/&$/, '');
url = url.replace(/\?$/, '');
document.location.href = url;
}
The above version as a function
function removeURLParam(url, param)
{
var urlparts= url.split('?');
if (urlparts.length>=2)
{
var prefix= encodeURIComponent(param)+'=';
var pars= urlparts[1].split(/[&;]/g);
for (var i=pars.length; i-- > 0;)
if (pars[i].indexOf(prefix, 0)==0)
pars.splice(i, 1);
if (pars.length > 0)
return urlparts[0]+'?'+pars.join('&');
else
return urlparts[0];
}
else
return url;
}
You should be using a library to do URI manipulation as it is more complicated than it seems on the surface to do it yourself. Take a look at: http://medialize.github.io/URI.js/
From what I can see, none of the above can handle normal parameters and array parameters. Here's one that does.
function removeURLParameter(param, url) {
url = decodeURI(url).split("?");
path = url.length == 1 ? "" : url[1];
path = path.replace(new RegExp("&?"+param+"\\[\\d*\\]=[\\w]+", "g"), "");
path = path.replace(new RegExp("&?"+param+"=[\\w]+", "g"), "");
path = path.replace(/^&/, "");
return url[0] + (path.length
? "?" + path
: "");
}
function addURLParameter(param, val, url) {
if(typeof val === "object") {
// recursively add in array structure
if(val.length) {
return addURLParameter(
param + "[]",
val.splice(-1, 1)[0],
addURLParameter(param, val, url)
)
} else {
return url;
}
} else {
url = decodeURI(url).split("?");
path = url.length == 1 ? "" : url[1];
path += path.length
? "&"
: "";
path += decodeURI(param + "=" + val);
return url[0] + "?" + path;
}
}
How to use it:
url = location.href;
-> http://example.com/?tags[]=single&tags[]=promo&sold=1
url = removeURLParameter("sold", url)
-> http://example.com/?tags[]=single&tags[]=promo
url = removeURLParameter("tags", url)
-> http://example.com/
url = addURLParameter("tags", ["single", "promo"], url)
-> http://example.com/?tags[]=single&tags[]=promo
url = addURLParameter("sold", 1, url)
-> http://example.com/?tags[]=single&tags[]=promo&sold=1
Of course, to update a parameter, just remove then add. Feel free to make a dummy function for it.
All of the responses on this thread have a flaw in that they do not preserve anchor/fragment parts of URLs.
So if your URL looks like:
http://dns-entry/path?parameter=value#fragment-text
and you replace 'parameter'
you will lose your fragment text.
The following is adaption of previous answers (bobince via LukePH) that addresses this problem:
function removeParameter(url, parameter)
{
var fragment = url.split('#');
var urlparts= fragment[0].split('?');
if (urlparts.length>=2)
{
var urlBase=urlparts.shift(); //get first part, and remove from array
var queryString=urlparts.join("?"); //join it back up
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;) { //reverse iteration as may be destructive
if (pars[i].lastIndexOf(prefix, 0)!==-1) { //idiom for string.startsWith
pars.splice(i, 1);
}
}
url = urlBase + (pars.length > 0 ? '?' + pars.join('&') : '');
if (fragment[1]) {
url += "#" + fragment[1];
}
}
return url;
}
I practically wrote the following function to process the url parameters and get the final status as a string and redirect the page. Hopefully it benefits.
function addRemoveUrlQuery(addParam = {}, removeParam = [], startQueryChar = '?'){
let urlParams = new URLSearchParams(window.location.search);
//Add param
for(let i in addParam){
if(urlParams.has(i)){ urlParams.set(i, addParam[i]); }
else { urlParams.append(i, addParam[i]); }
}
//Remove param
for(let i of removeParam){
if(urlParams.has(i)){
urlParams.delete(i);
}
}
if(urlParams.toString()){
return startQueryChar + urlParams.toString();
}
return '';
}
For example, when I click a button, I want the page value to be deleted and the category value to be added.
let button = document.getElementById('changeCategory');
button.addEventListener('click', function (e) {
window.location = addRemoveUrlQuery({'category':'cars'}, ['page']);
});
I think it was very useful!
another direct & simpler answer would be
let url = new URLSearchParams(location.search)
let key = 'some_key'
return url.has(key)
? location.href.replace(new RegExp(`[?&]${key}=${url.get(key)}`), '')
: location.href
If you have a polyfill for URLSearchParams or simply don't have to support Internet Explorer, that's what I would use like suggested in other answers here. If you don't want to depend on URLSearchParams, that's how I would do it:
function removeParameterFromUrl(url, parameter) {
const replacer = (m, p1, p2) => (p1 === '?' && p2 === '&' ? '?' : p2 || '')
return url.replace(new RegExp(`([?&])${parameter}=[^&#]+([&#])?`), replacer)
}
It will replace a parameter preceded by ? (p1) and followed by & (p2) with ? to make sure the list of parameters still starts with a question mark, otherwise, it will replace it with the next separator (p2): could be &, or #, or undefined which falls back to an empty string.
A modified version of solution by ssh_imov
function removeParam(uri, keyValue) {
var re = new RegExp("([&\?]"+ keyValue + "*$|" + keyValue + "&|[?&]" + keyValue + "(?=#))", "i");
return uri.replace(re, '');
}
Call like this
removeParam("http://google.com?q=123&q1=234&q2=567", "q1=234");
// returns http://google.com?q=123&q2=567
This returns the URL w/o ANY GET Parameters:
var href = document.location.href;
var search = document.location.search;
var pos = href.indexOf( search );
if ( pos !== -1 ){
href = href.slice( 0, pos );
console.log( href );
}
const params = new URLSearchParams(location.search)
params.delete('key_to_delete')
console.log(params.toString())
Glad you scrolled here.
I would suggest you to resolve this task by next possible solutions:
You need to support only modern browsers (Edge >= 17) - use URLSearchParams.delete() API. It is native and obviously is the most convenient way of solving this task.
If this is not an option, you may want to write a function to do this. Such a function does
do not change URL if a parameter is not present
remove URL parameter without a value, like http://google.com/?myparm
remove URL parameter with a value, like http://google.com/?myparm=1
remove URL parameter if is it in URL twice, like http://google.com?qp=1&qpqp=2&qp=1
Does not use for loop and not modify array during looping over it
is more functional
is more readable than regexp solutions
Before using make sure your URL is not encoded
Works in IE > 9 (ES5 version)
function removeParamFromUrl(url, param) { // url: string, param: string
var urlParts = url.split('?'),
preservedQueryParams = '';
if (urlParts.length === 2) {
preservedQueryParams = urlParts[1]
.split('&')
.filter(function(queryParam) {
return !(queryParam === param || queryParam.indexOf(param + '=') === 0)
})
.join('&');
}
return urlParts[0] + (preservedQueryParams && '?' + preservedQueryParams);
}
Fancy ES6 version
function removeParamFromUrlEs6(url, param) {
const [path, queryParams] = url.split('?');
let preservedQueryParams = '';
if (queryParams) {
preservedQueryParams = queryParams
.split('&')
.filter(queryParam => !(queryParam === param || queryParam.startsWith(`${param}=`)))
.join('&');
}
return `${path}${preservedQueryParams && `?${preservedQueryParams}`}`;
}
See how it works here
function removeParamInAddressBar(parameter) {
var url = document.location.href;
var urlparts = url.split('?');
if (urlparts.length >= 2) {
var urlBase = urlparts.shift();
var queryString = urlparts.join("?");
var prefix = encodeURIComponent(parameter) + '=';
var pars = queryString.split(/[&;]/g);
for (var i = pars.length; i-- > 0;) {
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
if (pars.length == 0) {
url = urlBase;
} else {
url = urlBase + '?' + pars.join('&');
}
window.history.pushState('', document.title, url); // push the new url in address bar
}
return url;
}
If you're into jQuery, there is a good query string manipulation plugin:
http://plugins.jquery.com/project/query-object
function removeQueryStringParameter(uri, key, value)
{
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '');
}
}
With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development.
I wrote the following function which accomplishes what I want to achieve:
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
Update (2020): URLSearchParams is now supported by all modern browsers.
The URLSearchParams utility can be useful for this in combination with window.location.search. For example:
if ('URLSearchParams' in window) {
var searchParams = new URLSearchParams(window.location.search);
searchParams.set("foo", "bar");
window.location.search = searchParams.toString();
}
Now foo has been set to bar regardless of whether or not it already existed.
However, the above assignment to window.location.search will cause a page load, so if that's not desirable use the History API as follows:
if ('URLSearchParams' in window) {
var searchParams = new URLSearchParams(window.location.search)
searchParams.set("foo", "bar");
var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
history.pushState(null, '', newRelativePathQuery);
}
Now you don't need to write your own regex or logic to handle the possible existence of query strings.
However, browser support is poor as it's currently experimental and only in use in recent versions of Chrome, Firefox, Safari, iOS Safari, Android Browser, Android Chrome and Opera. Use with a polyfill if you do decide to use it.
I have expanded the solution and combined it with another that I found to replace/update/remove the querystring parameters based on the users input and taking the urls anchor into consideration.
Not supplying a value will remove the parameter, supplying one will add/update the parameter. If no URL is supplied, it will be grabbed from window.location
function UpdateQueryString(key, value, url) {
if (!url) url = window.location.href;
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
hash;
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null) {
return url.replace(re, '$1' + key + "=" + value + '$2$3');
}
else {
hash = url.split('#');
url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
url += '#' + hash[1];
}
return url;
}
}
else {
if (typeof value !== 'undefined' && value !== null) {
var separator = url.indexOf('?') !== -1 ? '&' : '?';
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
url += '#' + hash[1];
}
return url;
}
else {
return url;
}
}
}
Update
There was a bug when removing the first parameter in the querystring, I have reworked the regex and test to include a fix.
Second Update
As suggested by #JarónBarends - Tweak value check to check against undefined and null to allow setting 0 values
Third Update
There was a bug where removing a querystring variable directly before a hashtag would lose the hashtag symbol which has been fixed
Fourth Update
Thanks #rooby for pointing out a regex optimization in the first RegExp object.
Set initial regex to ([?&]) due to issue with using (\?|&) found by #YonatanKarni
Fifth Update
Removing declaring hash var in if/else statement
Based on #amateur's answer (and now incorporating the fix from #j_walker_dev comment), but taking into account the comment about hash tags in the url I use the following:
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
var hash = '';
if( uri.indexOf('#') !== -1 ){
hash = uri.replace(/.*#/, '#');
uri = uri.replace(/#.*/, '');
}
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
return uri + separator + key + "=" + value + hash;
}
}
Edited to fix [?|&] in regex which should of course be [?&] as pointed out in the comments
Edit: Alternative version to support removing URL params as well. I have used value === undefined as the way to indicate removal. Could use value === false or even a separate input param as wanted.
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
if( value === undefined ) {
if (uri.match(re)) {
return uri.replace(re, '$1$2').replace(/[?&]$/, '').replaceAll(/([?&])&+/g, '$1').replace(/[?&]#/, '#');
} else {
return uri;
}
} else {
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
var hash = '';
if( uri.indexOf('#') !== -1 ){
hash = uri.replace(/.*#/, '#');
uri = uri.replace(/#.*/, '');
}
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
return uri + separator + key + "=" + value + hash;
}
}
}
See it in action at https://jsfiddle.net/cdt16wex/
You can use the browser's native URL API to do this in a fairly simple way, where key and value are your parameter name and parameter value respectively.
const url = new URL(location.href);
url.searchParams.set(key, value);
history.pushState(null, '', url);
This will preserve everything about the URL and only change or add the one query param. You can also use replaceState instead of pushState if you don't want it to create a new browser history entry.
Thanks to modern javascript, node.js and browsers support, we can get out of 3rd-party library whirlpool (jquery, query-string etc.) and DRY ourselves.
Here are javascript(node.js) and typescript version for a function that adds or updates query params of given url:
Javascript
const getUriWithParam = (baseUrl, params) => {
const Url = new URL(baseUrl);
const urlParams = new URLSearchParams(Url.search);
for (const key in params) {
if (params[key] !== undefined) {
urlParams.set(key, params[key]);
}
}
Url.search = urlParams.toString();
return Url.toString();
};
console.info('expected: https://example.com/?foo=bar');
console.log(getUriWithParam("https://example.com", {foo: "bar"}));
console.info('expected: https://example.com/slug?foo=bar#hash');
console.log(getUriWithParam("https://example.com/slug#hash", {foo: "bar"}));
console.info('expected: https://example.com/?bar=baz&foo=bar');
console.log(getUriWithParam("https://example.com?bar=baz", {foo: "bar"}));
console.info('expected: https://example.com/?foo=baz&bar=baz');
console.log(getUriWithParam("https://example.com?foo=bar&bar=baz", {foo: "baz"}));
Typescript
const getUriWithParam = (
baseUrl: string,
params: Record<string, any>
): string => {
const Url = new URL(baseUrl);
const urlParams: URLSearchParams = new URLSearchParams(Url.search);
for (const key in params) {
if (params[key] !== undefined) {
urlParams.set(key, params[key]);
}
}
Url.search = urlParams.toString();
return Url.toString();
};
For React Native
URL is not implemented in React Native. So you have to install react-native-url-polyfill beforehand.
For object params
See the second solution in this answer
Here is my library to do that: https://github.com/Mikhus/jsurl
var u = new Url;
u.query.param='value'; // adds or replaces the param
alert(u)
If it's not set or want to update with a new value you can use:
window.location.search = 'param=value'; // or param=new_value
This is in simple Javascript, by the way.
EDIT
You may want to try using the jquery query-object plugin
window.location.search =
jQuery.query.set("param", 5);
I realize this question is old and has been answered to death, but here's my stab at it. I'm trying to reinvent the wheel here because I was using the currently accepted answer and the mishandling of URL fragments recently bit me in a project.
The function is below. It's quite long, but it was made to be as resilient as possible. I would love suggestions for shortening/improving it. I put together a small jsFiddle test suite for it (or other similar functions). If a function can pass every one of the tests there, I say it's probably good to go.
Update: I came across a cool function for using the DOM to parse URLs, so I incorporated that technique here. It makes the function shorter and more reliable. Props to the author of that function.
/**
* Add or update a query string parameter. If no URI is given, we use the current
* window.location.href value for the URI.
*
* Based on the DOM URL parser described here:
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*
* #param (string) uri Optional: The URI to add or update a parameter in
* #param (string) key The key to add or update
* #param (string) value The new value to set for key
*
* Tested on Chrome 34, Firefox 29, IE 7 and 11
*/
function update_query_string( uri, key, value ) {
// Use window URL if no query string is provided
if ( ! uri ) { uri = window.location.href; }
// Create a dummy element to parse the URI with
var a = document.createElement( 'a' ),
// match the key, optional square brackets, an equals sign or end of string, the optional value
reg_ex = new RegExp( key + '((?:\\[[^\\]]*\\])?)(=|$)(.*)' ),
// Setup some additional variables
qs,
qs_len,
key_found = false;
// Use the JS API to parse the URI
a.href = uri;
// If the URI doesn't have a query string, add it and return
if ( ! a.search ) {
a.search = '?' + key + '=' + value;
return a.href;
}
// Split the query string by ampersands
qs = a.search.replace( /^\?/, '' ).split( /&(?:amp;)?/ );
qs_len = qs.length;
// Loop through each query string part
while ( qs_len > 0 ) {
qs_len--;
// Remove empty elements to prevent double ampersands
if ( ! qs[qs_len] ) { qs.splice(qs_len, 1); continue; }
// Check if the current part matches our key
if ( reg_ex.test( qs[qs_len] ) ) {
// Replace the current value
qs[qs_len] = qs[qs_len].replace( reg_ex, key + '$1' ) + '=' + value;
key_found = true;
}
}
// If we haven't replaced any occurrences above, add the new parameter and value
if ( ! key_found ) { qs.push( key + '=' + value ); }
// Set the new query string
a.search = '?' + qs.join( '&' );
return a.href;
}
window.location.search is read/write.
However - modifying the query string will redirect the page you're on and cause a refresh from the server.
If what you're attempting to do is maintain client side state (and potentially make it bookmark-able), you'll want to modify the URL hash instead of the query string, which keeps you on the same page (window.location.hash is read/write). This is how web sites like twitter.com do this.
You'll also want the back button to work, you'll have to bind javascript events to the hash change event, a good plugin for that is http://benalman.com/projects/jquery-hashchange-plugin/
Here's my approach: The location.params() function (shown below) can be used as a getter or setter. Examples:
Given the URL is http://example.com/?foo=bar&baz#some-hash,
location.params() will return an object with all the query parameters: {foo: 'bar', baz: true}.
location.params('foo') will return 'bar'.
location.params({foo: undefined, hello: 'world', test: true}) will change the URL to http://example.com/?baz&hello=world&test#some-hash.
Here is the params() function, which can optionally be assigned to the window.location object.
location.params = function(params) {
var obj = {}, i, parts, len, key, value;
if (typeof params === 'string') {
value = location.search.match(new RegExp('[?&]' + params + '=?([^&]*)[&#$]?'));
return value ? value[1] : undefined;
}
var _params = location.search.substr(1).split('&');
for (i = 0, len = _params.length; i < len; i++) {
parts = _params[i].split('=');
if (! parts[0]) {continue;}
obj[parts[0]] = parts[1] || true;
}
if (typeof params !== 'object') {return obj;}
for (key in params) {
value = params[key];
if (typeof value === 'undefined') {
delete obj[key];
} else {
obj[key] = value;
}
}
parts = [];
for (key in obj) {
parts.push(key + (obj[key] === true ? '' : '=' + obj[key]));
}
location.search = parts.join('&');
};
I know this is quite old but i want to fires my working version in here.
function addOrUpdateUrlParam(uri, paramKey, paramVal) {
var re = new RegExp("([?&])" + paramKey + "=[^&#]*", "i");
if (re.test(uri)) {
uri = uri.replace(re, '$1' + paramKey + "=" + paramVal);
} else {
var separator = /\?/.test(uri) ? "&" : "?";
uri = uri + separator + paramKey + "=" + paramVal;
}
return uri;
}
jQuery(document).ready(function($) {
$('#paramKey,#paramValue').on('change', function() {
if ($('#paramKey').val() != "" && $('#paramValue').val() != "") {
$('#uri').val(addOrUpdateUrlParam($('#uri').val(), $('#paramKey').val(), $('#paramValue').val()));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="width:100%" type="text" id="uri" value="http://www.example.com/text.php">
<label style="display:block;">paramKey
<input type="text" id="paramKey">
</label>
<label style="display:block;">paramValue
<input type="text" id="paramValue">
</label>
NOTE This is a modified version of #elreimundo
It's so simple with URLSearchParams, supported in all modern browsers (caniuse).
let p = new URLSearchParams();
p.set("foo", "bar");
p.set("name", "Jack & Jill?");
console.log("http://example.com/?" + p.toString());
If you want to modify the existing URL, construct the object like this: new URLSearchParams(window.location.search) and assign the string to window.location.search.
My take from here (compatible with "use strict"; does not really use jQuery):
function decodeURIParams(query) {
if (query == null)
query = window.location.search;
if (query[0] == '?')
query = query.substring(1);
var params = query.split('&');
var result = {};
for (var i = 0; i < params.length; i++) {
var param = params[i];
var pos = param.indexOf('=');
if (pos >= 0) {
var key = decodeURIComponent(param.substring(0, pos));
var val = decodeURIComponent(param.substring(pos + 1));
result[key] = val;
} else {
var key = decodeURIComponent(param);
result[key] = true;
}
}
return result;
}
function encodeURIParams(params, addQuestionMark) {
var pairs = [];
for (var key in params) if (params.hasOwnProperty(key)) {
var value = params[key];
if (value != null) /* matches null and undefined */ {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
}
}
if (pairs.length == 0)
return '';
return (addQuestionMark ? '?' : '') + pairs.join('&');
}
//// alternative to $.extend if not using jQuery:
// function mergeObjects(destination, source) {
// for (var key in source) if (source.hasOwnProperty(key)) {
// destination[key] = source[key];
// }
// return destination;
// }
function navigateWithURIParams(newParams) {
window.location.search = encodeURIParams($.extend(decodeURIParams(), newParams), true);
}
Example usage:
// add/update parameters
navigateWithURIParams({ foo: 'bar', boz: 42 });
// remove parameter
navigateWithURIParams({ foo: null });
// submit the given form by adding/replacing URI parameters (with jQuery)
$('.filter-form').submit(function(e) {
e.preventDefault();
navigateWithURIParams(decodeURIParams($(this).serialize()));
});
Based on the answer #ellemayo gave, I came up with the following solution that allows for disabling of the hash tag if desired:
function updateQueryString(key, value, options) {
if (!options) options = {};
var url = options.url || location.href;
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"), hash;
hash = url.split('#');
url = hash[0];
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null) {
url = url.replace(re, '$1' + key + "=" + value + '$2$3');
} else {
url = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
}
} else if (typeof value !== 'undefined' && value !== null) {
var separator = url.indexOf('?') !== -1 ? '&' : '?';
url = url + separator + key + '=' + value;
}
if ((typeof options.hash === 'undefined' || options.hash) &&
typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
Call it like this:
updateQueryString('foo', 'bar', {
url: 'http://my.example.com#hash',
hash: false
});
Results in:
http://my.example.com?foo=bar
Here is a shorter version that takes care of
query with or without a given parameter
query with multiple parameter values
query containing hash
Code:
var setQueryParameter = function(uri, key, value) {
var re = new RegExp("([?&])("+ key + "=)[^&#]*", "g");
if (uri.match(re))
return uri.replace(re, '$1$2' + value);
// need to add parameter to URI
var paramString = (uri.indexOf('?') < 0 ? "?" : "&") + key + "=" + value;
var hashIndex = uri.indexOf('#');
if (hashIndex < 0)
return uri + paramString;
else
return uri.substring(0, hashIndex) + paramString + uri.substring(hashIndex);
}
The regex description can be found here.
NOTE: This solution is based on #amateur answer, but with many improvements.
Code that appends a list of parameters to an existing url using ES6 and jQuery:
class UrlBuilder {
static appendParametersToUrl(baseUrl, listOfParams) {
if (jQuery.isEmptyObject(listOfParams)) {
return baseUrl;
}
const newParams = jQuery.param(listOfParams);
let partsWithHash = baseUrl.split('#');
let partsWithParams = partsWithHash[0].split('?');
let previousParams = '?' + ((partsWithParams.length === 2) ? partsWithParams[1] + '&' : '');
let previousHash = (partsWithHash.length === 2) ? '#' + partsWithHash[1] : '';
return partsWithParams[0] + previousParams + newParams + previousHash;
}
}
Where listOfParams is like
const listOfParams = {
'name_1': 'value_1',
'name_2': 'value_2',
'name_N': 'value_N',
};
Example of Usage:
UrlBuilder.appendParametersToUrl(urlBase, listOfParams);
Fast tests:
url = 'http://hello.world';
console.log('=> ', UrlParameters.appendParametersToUrl(url, null));
// Output: http://hello.world
url = 'http://hello.world#h1';
console.log('=> ', UrlParameters.appendParametersToUrl(url, null));
// Output: http://hello.world#h1
url = 'http://hello.world';
params = {'p1': 'v1', 'p2': 'v2'};
console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
// Output: http://hello.world?p1=v1&p2=v2
url = 'http://hello.world?p0=v0';
params = {'p1': 'v1', 'p2': 'v2'};
console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
// Output: http://hello.world?p0=v0&p1=v1&p2=v2
url = 'http://hello.world#h1';
params = {'p1': 'v1', 'p2': 'v2'};
console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
// Output: http://hello.world?p1=v1&p2=v2#h1
url = 'http://hello.world?p0=v0#h1';
params = {'p1': 'v1', 'p2': 'v2'};
console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
// Output: http://hello.world?p0=v0&p1=v1&p2=v2#h1
To give an code example for modifying window.location.search as suggested by Gal and tradyblix:
var qs = window.location.search || "?";
var param = key + "=" + value; // remember to URI encode your parameters
if (qs.length > 1) {
// more than just the question mark, so append with ampersand
qs = qs + "&";
}
qs = qs + param;
window.location.search = qs;
A different approach without using regular expressions. Supports 'hash' anchors at the end of the url as well as multiple question mark charcters (?). Should be slightly faster than the regular expression approach.
function setUrlParameter(url, key, value) {
var parts = url.split("#", 2), anchor = parts.length > 1 ? "#" + parts[1] : '';
var query = (url = parts[0]).split("?", 2);
if (query.length === 1)
return url + "?" + key + "=" + value + anchor;
for (var params = query[query.length - 1].split("&"), i = 0; i < params.length; i++)
if (params[i].toLowerCase().startsWith(key.toLowerCase() + "="))
return params[i] = key + "=" + value, query[query.length - 1] = params.join("&"), query.join("?") + anchor;
return url + "&" + key + "=" + value + anchor
}
Use this function to add, remove and modify query string parameter from URL based on jquery
/**
#param String url
#param object param {key: value} query parameter
*/
function modifyURLQuery(url, param){
var value = {};
var query = String(url).split('?');
if (query[1]) {
var part = query[1].split('&');
for (i = 0; i < part.length; i++) {
var data = part[i].split('=');
if (data[0] && data[1]) {
value[data[0]] = data[1];
}
}
}
value = $.extend(value, param);
// Remove empty value
for (i in value){
if(!value[i]){
delete value[i];
}
}
// Return url with modified parameter
if(value){
return query[0] + '?' + $.param(value);
} else {
return query[0];
}
}
Add new and modify existing parameter to url
var new_url = modifyURLQuery("http://google.com?foo=34", {foo: 50, bar: 45});
// Result: http://google.com?foo=50&bar=45
Remove existing
var new_url = modifyURLQuery("http://google.com?foo=50&bar=45", {bar: null});
// Result: http://google.com?foo=50
Here's my slightly different approach to this, written as an excercise
function addOrChangeParameters( url, params )
{
let splitParams = {};
let splitPath = (/(.*)[?](.*)/).exec(url);
if ( splitPath && splitPath[2] )
splitPath[2].split("&").forEach( k => { let d = k.split("="); splitParams[d[0]] = d[1]; } );
let newParams = Object.assign( splitParams, params );
let finalParams = Object.keys(newParams).map( (a) => a+"="+newParams[a] ).join("&");
return splitPath ? (splitPath[1] + "?" + finalParams) : (url + "?" + finalParams);
}
usage:
const url = "http://testing.com/path?empty&value1=test&id=3";
addOrChangeParameters( url, {value1:1, empty:"empty", new:0} )
"http://testing.com/path?empty=empty&value1=1&id=3&new=0"
This answer is just a small tweak of ellemayo's answer. It will automatically update the URL instead of just returning the updated string.
function _updateQueryString(key, value, url) {
if (!url) url = window.location.href;
let updated = ''
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
hash;
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null) {
updated = url.replace(re, '$1' + key + "=" + value + '$2$3');
}
else {
hash = url.split('#');
url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
url += '#' + hash[1];
}
updated = url;
}
}
else {
if (typeof value !== 'undefined' && value !== null) {
var separator = url.indexOf('?') !== -1 ? '&' : '?';
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
url += '#' + hash[1];
}
updated = url;
}
else {
updated = url;
}
}
window.history.replaceState({ path: updated }, '', updated);
}
Java script code to find a specific query string and replace its value *
('input.letter').click(function () {
//0- prepare values
var qsTargeted = 'letter=' + this.value; //"letter=A";
var windowUrl = '';
var qskey = qsTargeted.split('=')[0];
var qsvalue = qsTargeted.split('=')[1];
//1- get row url
var originalURL = window.location.href;
//2- get query string part, and url
if (originalURL.split('?').length > 1) //qs is exists
{
windowUrl = originalURL.split('?')[0];
var qs = originalURL.split('?')[1];
//3- get list of query strings
var qsArray = qs.split('&');
var flag = false;
//4- try to find query string key
for (var i = 0; i < qsArray.length; i++) {
if (qsArray[i].split('=').length > 0) {
if (qskey == qsArray[i].split('=')[0]) {
//exists key
qsArray[i] = qskey + '=' + qsvalue;
flag = true;
break;
}
}
}
if (!flag)// //5- if exists modify,else add
{
qsArray.push(qsTargeted);
}
var finalQs = qsArray.join('&');
//6- prepare final url
window.location = windowUrl + '?' + finalQs;
}
else {
//6- prepare final url
//add query string
window.location = originalURL + '?' + qsTargeted;
}
})
});
Here's an alternative method using the inbuilt properties of the anchor HTML element:
Handles multi-valued parameters.
No risk of modifying the # fragment, or anything other than the query string itself.
May be a little easier to read? But it is longer.
var a = document.createElement('a'),
getHrefWithUpdatedQueryString = function(param, value) {
return updatedQueryString(window.location.href, param, value);
},
updatedQueryString = function(url, param, value) {
/*
A function which modifies the query string
by setting one parameter to a single value.
Any other instances of parameter will be removed/replaced.
*/
var fragment = encodeURIComponent(param) +
'=' + encodeURIComponent(value);
a.href = url;
if (a.search.length === 0) {
a.search = '?' + fragment;
} else {
var didReplace = false,
// Remove leading '?'
parts = a.search.substring(1)
// Break into pieces
.split('&'),
reassemble = [],
len = parts.length;
for (var i = 0; i < len; i++) {
var pieces = parts[i].split('=');
if (pieces[0] === param) {
if (!didReplace) {
reassemble.push('&' + fragment);
didReplace = true;
}
} else {
reassemble.push(parts[i]);
}
}
if (!didReplace) {
reassemble.push('&' + fragment);
}
a.search = reassemble.join('&');
}
return a.href;
};
if you want to set multiple parameters at once:
function updateQueryStringParameters(uri, params) {
for(key in params){
var value = params[key],
re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
uri = uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
uri = uri + separator + key + "=" + value;
}
}
return uri;
}
same function as #amateur's
if jslint gives you an error add this after the for loop
if(params.hasOwnProperty(key))
There are a lot of awkward and unnecessarily complicated answers on this page. The highest rated one, #amateur's, is quite good, although it has a bit of unnecessary fluff in the RegExp. Here is a slightly more optimal solution with cleaner RegExp and a cleaner replace call:
function updateQueryStringParamsNoHash(uri, key, value) {
var re = new RegExp("([?&])" + key + "=[^&]*", "i");
return re.test(uri)
? uri.replace(re, '$1' + key + "=" + value)
: uri + separator + key + "=" + value
;
}
As an added bonus, if uri is not a string, you won't get errors for trying to call match or replace on something that may not implement those methods.
And if you want to handle the case of a hash (and you've already done a check for properly formatted HTML), you can leverage the existing function instead of writing a new function containing the same logic:
function updateQueryStringParams(url, key, value) {
var splitURL = url.split('#');
var hash = splitURL[1];
var uri = updateQueryStringParamsNoHash(splitURL[0]);
return hash == null ? uri : uri + '#' + hash;
}
Or you can make some slight changes to #Adam's otherwise excellent answer:
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=[^&#]*", "i");
if (re.test(uri)) {
return uri.replace(re, '$1' + key + "=" + value);
} else {
var matchData = uri.match(/^([^#]*)(#.*)?$/);
var separator = /\?/.test(uri) ? "&" : "?";
return matchData[0] + separator + key + "=" + value + (matchData[1] || '');
}
}
This should serve the purpose:
function updateQueryString(url, key, value) {
var arr = url.split("#");
var url = arr[0];
var fragmentId = arr[1];
var updatedQS = "";
if (url.indexOf("?") == -1) {
updatedQS = encodeURIComponent(key) + "=" + encodeURIComponent(value);
}
else {
updatedQS = addOrModifyQS(url.substring(url.indexOf("?") + 1), key, value);
}
url = url.substring(0, url.indexOf("?")) + "?" + updatedQS;
if (typeof fragmentId !== 'undefined') {
url = url + "#" + fragmentId;
}
return url;
}
function addOrModifyQS(queryStrings, key, value) {
var oldQueryStrings = queryStrings.split("&");
var newQueryStrings = new Array();
var isNewKey = true;
for (var i in oldQueryStrings) {
var currItem = oldQueryStrings[i];
var searchKey = key + "=";
if (currItem.indexOf(searchKey) != -1) {
currItem = encodeURIComponent(key) + "=" + encodeURIComponent(value);
isNewKey = false;
}
newQueryStrings.push(currItem);
}
if (isNewKey) {
newQueryStrings.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
}
return newQueryStrings.join("&");
}
By using jQuery we can do like below
var query_object = $.query_string;
query_object["KEY"] = "VALUE";
var new_url = window.location.pathname + '?'+$.param(query_object)
In variable new_url we will have new query parameters.
Reference: http://api.jquery.com/jquery.param/
I wanted something that:
Uses the browser's native URL API
Can add, update, get, or delete
Expects the query string after the hash e.g. for single page applications
function queryParam(options = {}) {
var defaults = {
method: 'set',
url: window.location.href,
key: undefined,
value: undefined,
}
for (var prop in defaults) {
options[prop] = typeof options[prop] !== 'undefined' ? options[prop] : defaults[prop]
}
const existing = (options.url.lastIndexOf('?') > options.url.lastIndexOf('#')) ? options.url.substr(options.url.lastIndexOf('?') + 1) : ''
const query = new URLSearchParams(existing)
if (options.method === 'set') {
query.set(options.key, options.value)
return `${options.url.replace(`?${existing}`, '')}?${query.toString()}`
} else if (options.method === 'get') {
const val = query.get(options.key)
let result = val === null ? val : val.toString()
return result
} else if (options.method === 'delete') {
query.delete(options.key)
let result = `${options.url.replace(`?${existing}`, '')}?${query.toString()}`
const lastChar = result.charAt(result.length - 1)
if (lastChar === '?') {
result = `${options.url.replace(`?${existing}`, '')}`
}
return result
}
}
// Usage:
let url = 'https://example.com/sandbox/#page/'
url = queryParam({
url,
method: 'set',
key: 'my-first-param',
value: 'me'
})
console.log(url)
url = queryParam({
url,
method: 'set',
key: 'my-second-param',
value: 'you'
})
console.log(url)
url = queryParam({
url,
method: 'set',
key: 'my-second-param',
value: 'whomever'
})
console.log(url)
url = queryParam({
url,
method: 'delete',
key: 'my-first-param'
})
console.log(url)
const mySecondParam = queryParam({
url,
method: 'get',
key: 'my-second-param',
})
console.log(mySecondParam)
url = queryParam({
url,
method: 'delete',
key: 'my-second-param'
})
console.log(url)
Yeah I had an issue where my querystring would overflow and duplicate, but this was due to my own sluggishness. so I played a bit and worked up some js jquery(actualy sizzle) and C# magick.
So i just realized that after the server has done with the passed values, the values doesn't matter anymore, there is no reuse, if the client wanted to do the same thing evidently it will always be a new request, even if its the same parameters being passed. And thats all clientside, so some caching/cookies etc could be cool in that regards.
JS:
$(document).ready(function () {
$('#ser').click(function () {
SerializeIT();
});
function SerializeIT() {
var baseUrl = "";
baseUrl = getBaseUrlFromBrowserUrl(window.location.toString());
var myQueryString = "";
funkyMethodChangingStuff(); //whatever else before serializing and creating the querystring
myQueryString = $('#fr2').serialize();
window.location.replace(baseUrl + "?" + myQueryString);
}
function getBaseUrlFromBrowserUrl(szurl) {
return szurl.split("?")[0];
}
function funkyMethodChangingStuff(){
//do stuff to whatever is in fr2
}
});
HTML:
<div id="fr2">
<input type="text" name="qURL" value="http://somewhere.com" />
<input type="text" name="qSPart" value="someSearchPattern" />
</div>
<button id="ser">Serialize! and go play with the server.</button>
C#:
using System.Web;
using System.Text;
using System.Collections.Specialized;
public partial class SomeCoolWebApp : System.Web.UI.Page
{
string weburl = string.Empty;
string partName = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
string loadurl = HttpContext.Current.Request.RawUrl;
string querySZ = null;
int isQuery = loadurl.IndexOf('?');
if (isQuery == -1) {
//If There Was no Query
}
else if (isQuery >= 1) {
querySZ = (isQuery < loadurl.Length - 1) ? loadurl.Substring(isQuery + 1) : string.Empty;
string[] getSingleQuery = querySZ.Split('?');
querySZ = getSingleQuery[0];
NameValueCollection qs = null;
qs = HttpUtility.ParseQueryString(querySZ);
weburl = qs["qURL"];
partName = qs["qSPart"];
//call some great method thisPageRocks(weburl,partName); or whatever.
}
}
}
Okay criticism is welcome (this was a nightly concoction so feel free to note adjustments). If this helped at all, thumb it up, Happy Coding.
No duplicates, each request as unique as you modified it, and due to how this is structured,easy to add more queries dynamicaly from wthin the dom.
I've been looking for an efficient way to do this but haven't been able to find it, basically what I need is that given this url for example:
http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100
I'd like to be able to change the URL in the src parameter with another value using javascript or jquery, is this possible?
The following solution combines other answers and handles some special cases:
The parameter does not exist in the original url
The parameter is the only parameter
The parameter is first or last
The new parameter value is the same as the old
The url ends with a ? character
\b ensures another parameter ending with paramName won't be matched
Solution:
function replaceUrlParam(url, paramName, paramValue)
{
if (paramValue == null) {
paramValue = '';
}
var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
if (url.search(pattern)>=0) {
return url.replace(pattern,'$1' + paramValue + '$2');
}
url = url.replace(/[?#]$/,'');
return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}
Known limitations:
Does not clear a parameter by setting paramValue to null, instead it sets it to empty string. See https://stackoverflow.com/a/25214672 if you want to remove the parameter.
Nowdays that's possible with native JS
var href = new URL('https://google.com?q=cats');
href.searchParams.set('q', 'dogs');
console.log(href.toString()); // https://google.com/?q=dogs
Wouldn't this be a better solution?
var text = 'http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100';
var newSrc = 'www.google.com';
var newText = text.replace(/(src=).*?(&)/,'$1' + newSrc + '$2');
EDIT:
added some clarity in code and kept 'src' in the resulting link
$1 represents first part within the () (i.e) src= and $2 represents the second part within the () (i.e) &, so this indicates you are going to change the value between src and &. More clear, it should be like this:
src='changed value'& // this is to be replaced with your original url
ADD-ON for replacing all the ocurrences:
If you have several parameters with the same name, you can append to the regex global flag, like this text.replace(/(src=).*?(&)/g,'$1' + newSrc + '$2'); and that will replaces all the values for those params that shares the same name.
Javascript now give a very useful functionnality to handle url parameters: URLSearchParams
var searchParams = new URLSearchParams(window.location.search);
searchParams.set('src','newSrc')
var newParams = searchParams.toString()
Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:
/search?searchquery=text and 'query' is provided.
In this case searchquery param value is changed.
Code:
function replaceUrlParam(url, paramName, paramValue){
var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
var newUrl=url
if(url.search(pattern)>=0){
newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
}
else{
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
return newUrl
}
In modern browsers (everything except IE9 and below), our lives are a little easier now with the new URL api
var url = new window.URL(document.location); // fx. http://host.com/endpoint?abc=123
url.searchParams.set("foo", "bar");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=bar
url.searchParams.set("foo", "ooft");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=ooft
// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
// Set new or modify existing parameter value.
queryParams.set("myParam", "myValue");
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());
Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:
history.pushState(null, null, "?"+queryParams.toString());
If you are having very narrow and specific use-case like replacing a particular parameter of given name that have alpha-numeric values with certain special characters capped upto certain length limit, you could try this approach:
urlValue.replace(/\bsrc=[0-9a-zA-Z_#.#+-]{1,50}\b/, 'src=' + newValue);
Example:
let urlValue = 'www.example.com?a=b&src=test-value&p=q';
const newValue = 'sucess';
console.log(urlValue.replace(/\bsrc=[0-9a-zA-Z_#.#+-]{1,50}\b/, 'src=' + newValue));
// output - www.example.com?a=b&src=sucess&p=q
I have get best solution to replace the URL parameter.
Following function will replace room value to 3 in the following URL.
http://example.com/property/?min=50000&max=60000&room=1&property_type=House
var newurl = replaceUrlParam('room','3');
history.pushState(null, null, newurl);
function replaceUrlParam(paramName, paramValue){
var url = window.location.href;
if (paramValue == null) {
paramValue = '';
}
var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
if (url.search(pattern)>=0) {
return url.replace(pattern,'$1' + paramValue + '$2');
}
url = url.replace(/[?#]$/,'');
return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}
Output
http://example.com/property/?min=50000&max=60000&room=3&property_type=House
Editing a Parameter
The set method of the URLSearchParams object sets the new value of the parameter.
After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.
The final new url can then be retrieved with the toString() method of the URL object.
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
// new value of "id" is set to "101"
search_params.set('id', '101');
// change the search property of the main url
url.search = search_params.toString();
// the new url string
var new_url = url.toString();
// output : http://demourl.com/path?id=101&topic=main
console.log(new_url);
Source - https://usefulangle.com/post/81/javascript-change-url-parameters
UpdatE: Make it into a nice function for you: http://jsfiddle.net/wesbos/KH25r/1/
function swapOutSource(url, newSource) {
params = url.split('&');
var src = params[0].split('=');
params.shift();
src[1] = newSource;
var newUrl = ( src.join('=') + params.join('&'));
return newUrl;
}
Then go at it!
var newUrl = swapOutSource("http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100","http://link/to/new.jpg");
console.log(newUrl);
If you look closely you'll see two surprising things about URLs: (1) they seem simple, but the details and corner cases are actually hard, (2) Amazingly JavaScript doesn't provide a full API for making working with them any easier. I think a full-fledged library is in order to avoid people re-inventing the wheel themselves or copying some random dude's clever, but likely buggy regex code snippet. Maybe try URI.js (http://medialize.github.io/URI.js/)
I use this method which:
replace the url in the history
return the value of the removed parameter
function getUrlParameterAndRemoveParameter(paramName) {
var url = window.location.origin + window.location.pathname;
var s = window.location.search.substring(1);
var pArray = (s == "" ? [] : s.split('&'));
var paramValue = null;
var pArrayNew = [];
for (var i = 0; i < pArray.length; i++) {
var pName = pArray[i].split('=');
if (pName[0] === paramName) {
paramValue = pName[1] === undefined ? true : decodeURIComponent(pName[1]);
}
else {
pArrayNew.push(pArray[i]);
}
}
url += (pArrayNew.length == 0 ? "" : "?" + pArrayNew.join('&'));
window.history.replaceState(window.history.state, document.title, url);
return paramValue;
}
In addition to #stenix, this worked perfectly to me
url = window.location.href;
paramName = 'myparam';
paramValue = $(this).val();
var pattern = new RegExp('('+paramName+'=).*?(&|$)')
var newUrl = url.replace(pattern,'$1' + paramValue + '$2');
var n=url.indexOf(paramName);
alert(n)
if(n == -1){
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
window.location.href = newUrl;
Here no need to save the "url" variable, just replace in current url
How about something like this:
<script>
function changeQueryVariable(keyString, replaceString) {
var query = window.location.search.substring(1);
var vars = query.split("&");
var replaced = false;
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == keyString) {
vars[i] = pair[0] + "="+ replaceString;
replaced = true;
}
}
if (!replaced) vars.push(keyString + "=" + replaceString);
return vars.join("&");
}
</script>
try this
var updateQueryStringParam = function (key, value) {
var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
urlQueryString = document.location.search,
newParam = key + '=' + value,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (urlQueryString) {
var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');
if( typeof value == 'undefined' || value == null || value == '' ) { // Remove param if value is empty
params = urlQueryString.replace(removeRegex, "$1");
params = params.replace( /[&;]$/, "" );
} else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
params = urlQueryString.replace(updateRegex, "$1" + newParam);
} else { // Otherwise, add it to end of query string
params = urlQueryString + '&' + newParam;
}
}
// no parameter was set so we don't need the question mark
params = params == '?' ? '' : params;
window.history.replaceState({}, "", baseUrl + params);
};
A solution without Regex, a little bit easier on the eye, one I was looking for
This supports ports, hash parameters etc.
Uses browsers attribute element as a parser.
function setUrlParameters(url, parameters) {
var parser = document.createElement('a');
parser.href = url;
url = "";
if (parser.protocol) {
url += parser.protocol + "//";
}
if (parser.host) {
url += parser.host;
}
if (parser.pathname) {
url += parser.pathname;
}
var queryParts = {};
if (parser.search) {
var search = parser.search.substring(1);
var searchParts = search.split("&");
for (var i = 0; i < searchParts.length; i++) {
var searchPart = searchParts[i];
var whitespaceIndex = searchPart.indexOf("=");
if (whitespaceIndex !== -1) {
var key = searchPart.substring(0, whitespaceIndex);
var value = searchPart.substring(whitespaceIndex + 1);
queryParts[key] = value;
} else {
queryParts[searchPart] = false;
}
}
}
var parameterKeys = Object.keys(parameters);
for (var i = 0; i < parameterKeys.length; i++) {
var parameterKey = parameterKeys[i];
queryParts[parameterKey] = parameters[parameterKey];
}
var queryPartKeys = Object.keys(queryParts);
var query = "";
for (var i = 0; i < queryPartKeys.length; i++) {
if (query.length === 0) {
query += "?";
}
if (query.length > 1) {
query += "&";
}
var queryPartKey = queryPartKeys[i];
query += queryPartKey;
if (queryParts[queryPartKey]) {
query += "=";
query += queryParts[queryPartKey];
}
}
url += query;
if (parser.hash) {
url += parser.hash;
}
return url;
}
2020 answer since I was missing the functionality to automatically delete a parameter, so:
Based on my favorite answer https://stackoverflow.com/a/20420424/6284674 :
I combined it with the ability to:
automatically delete an URL param if the value if null or '' based on answer https://stackoverflow.com/a/25214672/6284674
optionally push the updated URL directly in the window.location bar
IE support since it's only using regex and no URLSearchParams
JSfiddle: https://jsfiddle.net/MickV/zxc3b47u/
function replaceUrlParam(url, paramName, paramValue){
if(paramValue == null || paramValue == "")
return url
.replace(new RegExp('[?&]' + paramValue + '=[^&#]*(#.*)?$'), '$1')
.replace(new RegExp('([?&])' + paramValue + '=[^&]*&'), '$1');
url = url.replace(/\?$/,'');
var pattern = new RegExp('\\b('+paramName+'=).*?(&|$)')
if(url.search(pattern)>=0){
return url.replace(pattern,'$1' + paramValue + '$2');
}
return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
// Orginal URL (default jsfiddle console URL)
//https://fiddle.jshell.net/_display/?editor_console=true
console.log(replaceUrlParam(window.location.href,'a','2'));
//https://fiddle.jshell.net/_display/?editor_console=true&a=2
console.log(replaceUrlParam(window.location.href,'a',''));
//https://fiddle.jshell.net/_display/?editor_console=true
console.log(replaceUrlParam(window.location.href,'a',3));
//https://fiddle.jshell.net/_display/?editor_console=true&a=3
console.log(replaceUrlParam(window.location.href,'a', null));
//https://fiddle.jshell.net/_display/?editor_console=true&
//Optionally also update the replaced URL in the window location bar
//Note: This does not work in JSfiddle, but it does in a normal browser
function pushUrl(url){
window.history.pushState("", "", replaceUrlParam(window.location.href,'a','2'));
}
pushUrl(replaceUrlParam(window.location.href,'a','2'));
//https://fiddle.jshell.net/_display/?editor_console=true&a=2
pushUrl(replaceUrlParam(window.location.href,'a',''));
//https://fiddle.jshell.net/_display/?editor_console=true
pushUrl(replaceUrlParam(window.location.href,'a',3));
//https://fiddle.jshell.net/_display/?editor_console=true&a=3
pushUrl(replaceUrlParam(window.location.href,'a', null));
//https://fiddle.jshell.net/_display/?editor_console=true&
Here is function which replaces url param with paramVal
function updateURLParameter(url, param, paramVal){
if(!url.includes('?')){
return url += '?' + param + '=' + paramVal;
}else if(!url.includes(param)){
return url += '&' + param + '=' + paramVal;
}else {
let paramStartIndex = url.search(param);
let paramEndIndex = url.indexOf('&', paramStartIndex);
if (paramEndIndex == -1){
paramEndIndex = url.length;
}
let brands = url.substring(paramStartIndex, paramEndIndex);
return url.replace(brands, param + '=' + paramVal);
}
}
A lengthier, but maybe more flexible, answer that relies on two functions. The first one produces a key/value dictionary with all the parameters, the other one doing the substitution itself. This should work on old browsers, and can also create the parameter when it doesn't exist.
var get_all_params=function(url)
{
var regexS = /(?<=&|\?)([^=]*=[^&#]*)/;
var regex = new RegExp( regexS,'g' );
var results = url.match(regex);
if(results==null)
{
return {};
}
else
{
returned={};
for(i=0;i<results.length;i++)
{
var tmp=results[i];
var regexS2="([^=]+)=([^=]+)";
var regex2 = new RegExp( regexS2 );
var results2 = regex2.exec(tmp );
returned[results2[1]]=results2[2];
}
return returned;
}
}
var replace_param=function(url, param, value)
{
var get_params=get_all_params(url);
var base_url=url.split("?");
get_params[param]=value;
var new_params=Array();
for(key in get_params)
{
new_params.push(key+"="+get_params[key]);
}
return base_url[0]+"?"+new_params.join("&");
}
Exemple of call :
var url ="https://geoserver.xxx.com/geoserver/project?service=WFS&version=1.0.0&request=GetFeature&typename=localities";
url=replace_param(url, "service","WMS");
I have this URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
what I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified (10).
I've extended Sujoy's code to make up a function.
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
Function Calls:
var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');
window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));
Updated version that also take care of the anchors on the URL.
function updateURLParameter(url, param, paramVal)
{
var TheAnchor = null;
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL)
{
var tmpAnchor = additionalURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheAnchor)
additionalURL = TheParams;
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++)
{
if(tempArray[i].split('=')[0] != param)
{
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
else
{
var tmpAnchor = baseURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheParams)
baseURL = TheParams;
}
if(TheAnchor)
paramVal += "#" + TheAnchor;
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
I think you want the query plugin.
E.g.:
window.location.search = jQuery.query.set("rows", 10);
This will work regardless of the current state of rows.
Quick little solution in pure js, no plugins needed:
function replaceQueryParam(param, newval, search) {
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
}
Call it like this:
window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)
Or, if you want to stay on the same page and replace multiple params:
var str = window.location.search
str = replaceQueryParam('rows', 55, str)
str = replaceQueryParam('cols', 'no', str)
window.location = window.location.pathname + str
edit, thanks Luke: To remove the parameter entirely, pass false or null for the value: replaceQueryParam('rows', false, params). Since 0 is also falsy, specify '0'.
To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.
You can use query-string as follows:
// parse the query string into an object
var q = queryString.parse(location.search);
// set the `row` property
q.rows = 10;
// convert the object to a query string
// and overwrite the existing query string
location.search = queryString.stringify(q);
A modern approach to this is to use native standard based URLSearchParams. It's supported by all major browsers, except for IE where they're polyfills available
const paramsString = "site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc"
const searchParams = new URLSearchParams(paramsString);
searchParams.set('rows', 10);
console.log(searchParams.toString()); // return modified string.
Ben Alman has a good jquery querystring/url plugin here that allows you to manipulate the querystring easily.
As requested -
Goto his test page here
In firebug enter the following into the console
jQuery.param.querystring(window.location.href, 'a=3&newValue=100');
It will return you the following amended url string
http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3
Notice the a querystring value for a has changed from X to 3 and it has added the new value.
You can then use the new url string however you wish e.g
using document.location = newUrl or change an anchor link etc
This is the modern way to change URL parameters:
function setGetParam(key,value) {
if (history.pushState) {
var params = new URLSearchParams(window.location.search);
params.set(key, value);
var newUrl = window.location.origin
+ window.location.pathname
+ '?' + params.toString();
window.history.pushState({path:newUrl},'',newUrl);
}
}
you can do it via normal JS also
var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1];
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
if(tempArray[i].indexOf("rows") == -1){
newAdditionalURL += temp+tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;
Use URLSearchParams to check, get and set the parameters value into URL
Here is the example to get the current URL and set new parameter and update the URL or reload the page as per your needs
var rows = 5; // value that you want to set
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
url.search = url.searchParams;
url = url.toString();
// if you want to append into URL without reloading the page
history.pushState({}, null, url);
// want to reload the window with a new param
window.location = url;
2020 Solution: sets the variable or removes iti if you pass null or undefined to the value.
var setSearchParam = function(key, value) {
if (!window.history.pushState) {
return;
}
if (!key) {
return;
}
var url = new URL(window.location.href);
var params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) {
params.delete(key);
} else {
params.set(key, value);
}
url.search = params;
url = url.toString();
window.history.replaceState({url: url}, null, url);
}
Would a viable alternative to String manipulation be to set up an html form and just modify the value of the rows element?
So, with html that is something like
<form id='myForm' target='site.fwx'>
<input type='hidden' name='position' value='1'/>
<input type='hidden' name='archiveid' value='5000'/>
<input type='hidden' name='columns' value='5'/>
<input type='hidden' name='rows' value='20'/>
<input type='hidden' name='sorting' value='ModifiedTimeAsc'/>
</form>
With the following JavaScript to submit the form
var myForm = document.getElementById('myForm');
myForm.rows.value = yourNewValue;
myForm.submit();
Probably not suitable for all situations, but might be nicer than parsing the URL string.
URL query parameters can be easily modified using URLSearchParams and History interfaces:
// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
// Set new or modify existing parameter value.
//queryParams.set("myParam", "myValue");
queryParams.set("rows", "10");
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());
Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:
history.pushState(null, null, "?"+queryParams.toString());
https://zgadzaj.com/development/javascript/how-to-change-url-query-parameter-with-javascript-only
You can use this my library to do the job: https://github.com/Mikhus/jsurl
var url = new Url('site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc');
url.query.rows = 10;
alert( url);
Consider this one:
const myUrl = new URL("http://www.example.com?columns=5&rows=20");
myUrl.searchParams.set('rows', 10);
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10
myUrl.searchParams.set('foo', 'bar'); // add new param
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10&foo=bar
It will do exactly the same thing you required. Please note URL must have correct format. In your example you have to specify protocol (either http or https)
I wrote a little helper function that works with any select. All you need to do is add the class "redirectOnChange" to any select element, and this will cause the page to reload with a new/changed querystring parameter, equal to the id and value of the select, e.g:
<select id="myValue" class="redirectOnChange">
<option value="222">test222</option>
<option value="333">test333</option>
</select>
The above example would add "?myValue=222" or "?myValue=333" (or using "&" if other params exist), and reload the page.
jQuery:
$(document).ready(function () {
//Redirect on Change
$(".redirectOnChange").change(function () {
var href = window.location.href.substring(0, window.location.href.indexOf('?'));
var qs = window.location.href.substring(window.location.href.indexOf('?') + 1, window.location.href.length);
var newParam = $(this).attr("id") + '=' + $(this).val();
if (qs.indexOf($(this).attr("id") + '=') == -1) {
if (qs == '') {
qs = '?'
}
else {
qs = qs + '&'
}
qs = qs + newParam;
}
else {
var start = qs.indexOf($(this).attr("id") + "=");
var end = qs.indexOf("&", start);
if (end == -1) {
end = qs.length;
}
var curParam = qs.substring(start, end);
qs = qs.replace(curParam, newParam);
}
window.location.replace(href + '?' + qs);
});
});
Using javascript URL:
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
window.location = url;
var url = new URL(window.location.href);
var search_params = url.searchParams;
search_params.set("param", value);
url.search = search_params.toString();
var new_url = url.pathname + url.search;
window.history.replaceState({}, '', new_url);
Here I have taken Adil Malik's answer and fixed the 3 issues I identified with it.
/**
* Adds or updates a URL parameter.
*
* #param {string} url the URL to modify
* #param {string} param the name of the parameter
* #param {string} paramVal the new value for the parameter
* #return {string} the updated URL
*/
self.setParameter = function (url, param, paramVal){
// http://stackoverflow.com/a/10997390/2391566
var parts = url.split('?');
var baseUrl = parts[0];
var oldQueryString = parts[1];
var newParameters = [];
if (oldQueryString) {
var oldParameters = oldQueryString.split('&');
for (var i = 0; i < oldParameters.length; i++) {
if(oldParameters[i].split('=')[0] != param) {
newParameters.push(oldParameters[i]);
}
}
}
if (paramVal !== '' && paramVal !== null && typeof paramVal !== 'undefined') {
newParameters.push(param + '=' + encodeURI(paramVal));
}
if (newParameters.length > 0) {
return baseUrl + '?' + newParameters.join('&');
} else {
return baseUrl;
}
}
In the URLSearchParams documentation, there's a very clean way of doing this, without affecting the history stack.
// URL: https://example.com?version=1.0
const params = new URLSearchParams(location.search);
params.set('version', 2.0);
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?version=2.0
Similarily, to remove a parameter
params.delete('version')
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?
let url= new URL("https://example.com/site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc")
url.searchParams.set('rows', 10)
console.log(url.toString())
Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:
window.history.replaceState('object or string', 'Title', 'page.html' + editParams('sorting', ModifiedTimeAsc));
// background functions below:
// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
key = encodeURI(key);
var params = getSearchParameters();
if (Object.keys(params).length === 0) {
if (value !== false)
return '?' + key + '=' + encodeURI(value);
else
return '';
}
if (value !== false)
params[key] = encodeURI(value);
else
delete params[key];
if (Object.keys(params).length === 0)
return '';
return '?' + $.map(params, function (value, key) {
return key + '=' + value;
}).join('&');
}
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
My solution:
const setParams = (data) => {
if (typeof data !== 'undefined' && typeof data !== 'object') {
return
}
let url = new URL(window.location.href)
const params = new URLSearchParams(url.search)
for (const key of Object.keys(data)) {
if (data[key] == 0) {
params.delete(key)
} else {
params.set(key, data[key])
}
}
url.search = params
url = url.toString()
window.history.replaceState({ url: url }, null, url)
}
Then just call "setParams" and pass an object with data you want to set.
Example:
$('select').on('change', e => {
const $this = $(e.currentTarget)
setParams({ $this.attr('name'): $this.val() })
})
In my case I had to update a html select input when it changes and if the value is "0", remove the parameter. You can edit the function and remove the parameter from the url if the object key is "null" as well.
Hope this helps yall
If you want to change the url in address bar:
const search = new URLSearchParams(location.search);
search.set('rows', 10);
location.search = search.toString();
Note, changing location.search reloads the page.
Here is a simple solution using the query-string library.
const qs = require('query-string')
function addQuery(key, value) {
const q = qs.parse(location.search)
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
// if you are using Turbolinks
// add this: Turbolinks.visit(url)
}
// Usage
addQuery('page', 2)
If you are using react without react-router
export function useAddQuery() {
const location = window.location;
const addQuery = useCallback(
(key, value) => {
const q = qs.parse(location.search);
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
},
[location]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
If you are using react with react-router
export function useAddQuery() {
const location = useLocation();
const history = useHistory();
const addQuery = useCallback(
(key, value) => {
let pathname = location.pathname;
let searchParams = new URLSearchParams(location.search);
searchParams.set(key, value);
history.push({
pathname: pathname,
search: searchParams.toString()
});
},
[location, history]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
PS: qs is the import from query-string module.
Another variation on Sujoy's answer. Just changed the variable names & added a namespace wrapper:
window.MyNamespace = window.MyNamespace || {};
window.MyNamespace.Uri = window.MyNamespace.Uri || {};
(function (ns) {
ns.SetQueryStringParameter = function(url, parameterName, parameterValue) {
var otherQueryStringParameters = "";
var urlParts = url.split("?");
var baseUrl = urlParts[0];
var queryString = urlParts[1];
var itemSeparator = "";
if (queryString) {
var queryStringParts = queryString.split("&");
for (var i = 0; i < queryStringParts.length; i++){
if(queryStringParts[i].split('=')[0] != parameterName){
otherQueryStringParameters += itemSeparator + queryStringParts[i];
itemSeparator = "&";
}
}
}
var newQueryStringParameter = itemSeparator + parameterName + "=" + parameterValue;
return baseUrl + "?" + otherQueryStringParameters + newQueryStringParameter;
};
})(window.MyNamespace.Uri);
Useage is now:
var changedUrl = MyNamespace.Uri.SetQueryStringParameter(originalUrl, "CarType", "Ford");
I too have written a library for getting and setting URL query parameters in JavaScript.
Here is an example of its usage.
var url = Qurl.create()
, query
, foo
;
Get query params as an object, by key, or add/change/remove.
// returns { foo: 'bar', baz: 'qux' } for ?foo=bar&baz=qux
query = url.query();
// get the current value of foo
foo = url.query('foo');
// set ?foo=bar&baz=qux
url.query('foo', 'bar');
url.query('baz', 'qux');
// unset foo, leaving ?baz=qux
url.query('foo', false); // unsets foo
I was looking for the same thing and found: https://github.com/medialize/URI.js which is quite nice :)
-- Update
I found a better package: https://www.npmjs.org/package/qs it also deals with arrays in get params.
No library, using URL() WebAPI (https://developer.mozilla.org/en-US/docs/Web/API/URL)
function setURLParameter(url, parameter, value) {
let url = new URL(url);
if (url.searchParams.get(parameter) === value) {
return url;
}
url.searchParams.set(parameter, value);
return url.href;
}
This doesn't work on IE: https://developer.mozilla.org/en-US/docs/Web/API/URL#Browser_compatibility
I know this is an old question. I have enhanced the function above to add or update query params. Still a pure JS solution only.
function addOrUpdateQueryParam(param, newval, search) {
var questionIndex = search.indexOf('?');
if (questionIndex < 0) {
search = search + '?';
search = search + param + '=' + newval;
return search;
}
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
var indexOfEquals = query.indexOf('=');
return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
}
my function support removing param
function updateURLParameter(url, param, paramVal, remove = false) {
var newAdditionalURL = '';
var tempArray = url.split('?');
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var rows_txt = '';
if (additionalURL)
newAdditionalURL = decodeURI(additionalURL) + '&';
if (remove)
newAdditionalURL = newAdditionalURL.replace(param + '=' + paramVal, '');
else
rows_txt = param + '=' + paramVal;
window.history.replaceState('', '', (baseURL + "?" + newAdditionalURL + rows_txt).replace('?&', '?').replace('&&', '&').replace(/\&$/, ''));
}