How to add query parameter to url in jquery?

Member

by natalia , in category: JavaScript , 2 years ago

How to add query parameter to url in jquery?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by brisa , a year ago

@natalia You can use vanilla javascript and function below as an example to add a query parameter to URL, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function addQueryParams(key, val) {
    return window.location.href
        .replace(RegExp("([?&]" + key + "(?=[=&#]|$)[^#&]*|(?=#|$))"), "&" + key + "=" + encodeURIComponent(val))
        .replace(/^([^?&]+)&/, "$1?");
}

let url = addQueryParams('query', 'test');
// new url
console.log(url)
// redirect to new url
window.location.href = url;

Member

by berta , a year ago

@natalia 

You can add query parameters to a URL using jQuery by appending them to the end of the URL. Here's an example code:

1
2
3
4
5
6
7
8
// Get the current URL
var url = window.location.href;

// Append the query parameter
url += '?param=value';

// Redirect to the updated URL
window.location.href = url;


In the above code, window.location.href retrieves the current URL, += appends the query parameter param=value to the URL, and window.location.href = url redirects the page to the updated URL.


If you want to add a query parameter to a URL without redirecting the page, you can use jQuery's param() method. Here's an example code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Get the current URL
var url = window.location.href;

// Add the query parameter
var newUrl = $.param({ param: 'value' });

// Concatenate the new query string with the URL
var finalUrl = url.split('?')[0] + '?' + newUrl;

// Use the final URL
console.log(finalUrl);


In this code, $.param({ param: 'value' }) creates a new query string with the parameter param and value value. Then, we concatenate the new query string with the original URL to create a final URL with the added parameter.