In this blog post, we will learn how to add a query string to a URL using jQuery. A query string is a part of the URL that assigns values to specified parameters. It usually starts with a question mark (?) followed by key-value pairs, which are separated by an equal sign (=). Multiple key-value pairs are separated by an ampersand (&).
For example, consider the following URL with a query string:
https://www.example.com?parameter1=value1¶meter2=value2
Here, we have a query string with two parameters – parameter1 and parameter2 – and their respective values being value1 and value2.
Adding Query String to URL using jQuery
To add a query string to a URL using jQuery, we can create a function called addQueryString that takes two arguments – url and params. The url argument represents the base URL, and the params argument is an object containing key-value pairs of the parameters and their values. The function will return a URL with the query string appended.
Here’s the code for the addQueryString function:
<script> function addQueryString(url, params) { var queryString = $.param(params); if (url.indexOf('?') !== -1) { url += '&' + queryString; } else { url += '?' + queryString; } return url; } </script>
To use the addQueryString function, you need to include the jQuery library in your HTML file, as the function uses the $.param() method provided by jQuery:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Example Usage
Let’s say we have the following URL and parameters:
URL: https://www.example.com Parameters: - parameter1: value1 - parameter2: value2
To add the query string to the URL, we can pass the URL and parameters to the addQueryString function:
<script> var url = "https://www.example.com"; var params = { parameter1: "value1", parameter2: "value2" }; var urlWithQueryString = addQueryString(url, params); console.log(urlWithQueryString); // Output: https://www.example.com?parameter1=value1¶meter2=value2 </script>
And that’s it! Now you know how to add a query string to a URL using jQuery. This function can be very useful when you need to create URLs with dynamic values for parameters.