How to add or update query string parameter to current url in Javascript
In this post, I will let you know how to add or update query string parameter to current URL using Javascript.
- 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;
- }
- }
In above example, you will need to pass three argument, first will be your current URL and second will be key which you want to add/update and last argument will be the value of key.
using below example how to use and update a herf attribute
- $(".user_nav").each(function () {
- var $that = $(this);
- var oldurl = $that.attr('href');
- var nreUrl = updateQueryStringParameter(oldurl, 'testKey', 'testValue');
- $that.attr('href', nreUrl);
- });
Comments
Post a Comment