Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add or update a query string parameter?

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.

like image 569
amateur Avatar asked May 14 '11 00:05

amateur


People also ask

How do I add a query parameter to my postman?

To send a query parameter, add it directly to the URL or open Params and enter the name and value. When you enter your query parameters in either the URL or the Params fields, these values will update everywhere they're used in Postman. Parameters aren't automatically URL-encoded.

How do I change the URL of a query parameter?

The value of a parameter can be updated with the set() method of URLSearchParams object. 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.


2 Answers

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;   } } 
like image 150
amateur Avatar answered Oct 15 '22 13:10

amateur


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.

like image 33
Anthony Manning-Franklin Avatar answered Oct 15 '22 13:10

Anthony Manning-Franklin