Add or remove query string

How to add or remove query string in URL without page refresh

You can add/remove query string from URL without reloading page in javascript. Generally URL changes by page reloading. When URL changes page gets refresh and new content appears on page.

e.g. Go

Here when we click 'Go' it goes to new URL with query string.

 

HTML5 gave you facility to change URL using pushState function to change URL and append data using ajax.

e.g. history.pushState({state:1, rand: Math.random()}, '', "?page="+1);

history.pushState function is used to add history state. It takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL.


You can test code by clicking following buttons



Use following code function to modify query string without page reload

//Add jquery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<script>
//Define variable
var objQueryString={};

//Get querystring value
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

//Add or modify querystring
function changeUrl(key,value) {
	//Get query string value
	var searchUrl=location.search;
	if(searchUrl.indexOf("?")== "-1") {
		var urlValue='?'+key+'='+value;
		history.pushState({state:1, rand: Math.random()}, '', urlValue);
	}
	else {
		//Check for key in query string, if not present
		if(searchUrl.indexOf(key)== "-1") {
			var urlValue=searchUrl+'&'+key+'='+value;
		}
		else {	//If key present in query string
			oldValue = getParameterByName(key);
			if(searchUrl.indexOf("?"+key+"=")!= "-1") {
				urlValue = searchUrl.replace('?'+key+'='+oldValue,'?'+key+'='+value);
			}
			else {
				urlValue = searchUrl.replace('&'+key+'='+oldValue,'&'+key+'='+value);	
			}
		}
		history.pushState({state:1, rand: Math.random()}, '', urlValue);
		//history.pushState function is used to add history state.
		//It takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL.
	}
	objQueryString.key=value;
	sendAjaxReq(objQueryString);
}

//Used to display data in webpage from ajax
function sendAjaxReq(objQueryString) {
	$.post('test.php', objQueryString, function(data) {
		//alert(data);
	})
}


//Function used to remove querystring
function removeQString(key) {
	var urlValue=document.location.href;
	
	//Get query string value
	var searchUrl=location.search;
	
	if(key!="") {
		oldValue = getParameterByName(key);
		removeVal=key+"="+oldValue;
		if(searchUrl.indexOf('?'+removeVal+'&')!= "-1") {
			urlValue=urlValue.replace('?'+removeVal+'&','?');
		}
		else if(searchUrl.indexOf('&'+removeVal+'&')!= "-1") {
			urlValue=urlValue.replace('&'+removeVal+'&','&');
		}
		else if(searchUrl.indexOf('?'+removeVal)!= "-1") {
			urlValue=urlValue.replace('?'+removeVal,'');
		}
		else if(searchUrl.indexOf('&'+removeVal)!= "-1") {
			urlValue=urlValue.replace('&'+removeVal,'');
		}
	}
	else {
		var searchUrl=location.search;
		urlValue=urlValue.replace(searchUrl,'');
	}
	history.pushState({state:1, rand: Math.random()}, '', urlValue);
}

</script>

<div>
	<input type="button" value="Add id" onClick="changeUrl('id','2')" />
	<input type="button" value="Add category" onClick="changeUrl('category','mobile')" />
	<input type="button" value="Add item" onClick="changeUrl('item','samsung')" />

	<input type="button" value="Remove id" onClick="removeQString('id','2')" />
	<input type="button" value="Remove category" onClick="removeQString('category')" />
	<input type="button" value="Remove item" onClick="removeQString('item')" />
	<input type="button" value="Remove query string" onClick="removeQString('')" />
</div>

Thank you very much!
By Friend at 2017-08-04 05:00:21
Hi James, You can write this function in any external javascript page. As given in example, you may have link or button <input type="button" value="Add id" onClick="changeUrl('id','2')" /> You have to call function changeUrl only with parameters in URL.
By Mukesh kumar at 2017-02-17 20:08:41
Hello, Where to write this function? Please guide.
By James at 2017-02-16 03:50:22
Name
Email
Comments
Back
Funding

We need your support to operate it properly. We have lots of ideas but less fund, so help us with your funding.

Thoughts for the day

If a country is to be corruption free and become a nation of beautiful minds, I strongly feel there are three key societal members who can make a difference. They are the father, the mother and the teacher.

Dr. A.P.J. Abdul Kalam
Polls
Which device you use most for facebook application?
Laptop/PC
20%

 


Android
53%

 


IOS
13%

 


Blackberry
14%

 


Tutorial On Request
Q. Ask us for any tutorial or any thing which helps to build your career better.
Email:
Query: