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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With