How to Create Query Parameters in JavaScript ?
Last Updated :
25 Jun, 2024
Creating query parameters in JavaScript involves appending key-value pairs to a URL after the `?` character. This process is essential for passing data to web servers via URLs, enabling dynamic and interactive web applications through GET requests and URL manipulation.
Example:
Input: {'website':'geeks', 'location':'india'}
Output: website=geeks&location=india
There are several approaches to creating query parameters in JavaScript which are as follows:
Using URLSearchParams
The URLSearchParams interface provides methods to work with query strings of a URL.
Example: To demonstrate creating query parameters using JavaScript.
JavaScript
const params = new URLSearchParams();
params.append('website', 'geeks');
params.append('location', 'india');
const queryString = params.toString();
const url = `https://example.com?${queryString}`;
console.log(url);
Outputhttps://example.com?website=geeks&location=india
Using Template Literals
Manually construct the query string using template literals for simple scenarios.
Example: To demonstrate creating query parameters using JavaScript.
JavaScript
const website = 'geeks';
const location = 'india';
const url = `https://example.com?website=${website}&location=${location}`;
console.log(url);
Outputhttps://example.com?website=geeks&location=india
Using a Helper Function
Create a reusable function to generate query strings from an object of parameters.
Example: To demonstrate creating query parameters using JavaScript.
JavaScript
function createQueryString(params) {
return Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');
}
const params = { website: 'geeks', location: 'india' };
const queryString = createQueryString(params);
const url = `https://example.com?${queryString}`;
console.log(url);
Outputhttps://example.com?website=geeks&location=india
Using URL and URLSearchParams (ES6)
Modern approach using URL and URLSearchParams to manipulate URLs and query parameters.
Example: To demonstrate creating query parameters using JavaScript.
JavaScript
const url = new URL('https://example.com');
url.searchParams.append('website', 'geeks');
url.searchParams.append('location', 'india');
console.log(url.toString());
Outputhttps://example.com/?website=geeks&location=india
Handling Existing Query Parameters
Modifying an existing URL with query parameters.
Example: To demonstrate creating query parameters using JavaScript.
JavaScript
const url = new URL('https://example.com?website=geeks');
url.searchParams.set('website', 'geeks');
url.searchParams.set('location', 'india');
console.log(url.toString());
Outputhttps://example.com/?website=geeks&location=india
Using a Custom Function to Convert JSON to Query String
Convert a JSON object into a GET query parameter using a custom function.
Example: To demonstrate creating query parameters using JavaScript.
JavaScript
function encodeQuery(data){
let query = ""
for (let d in data)
query += encodeURIComponent(d) + '=' +
encodeURIComponent(data[d]) + '&'
return query.slice(0, -1);
}
const data = { website: 'geeks', location: 'india' };
const queryString = encodeQuery(data);
const url = `https://example.com?${queryString}`;
console.log(url);
Outputhttps://example.com?website=geeks&location=india
Using GET request
Get request given a JSON object using javaScript. GET query parameters in an URL are just a string of key-value pairs connected with the symbol &. To convert a JSON object into a GET query parameter we can use the following approach.
- Make a variable query.
- Loop through all the keys and values of the json and attach them together with ‘&’ symbol.
Examples:
Input: {'website':'geeks', 'location':'india'}
Output: website=geeks&location=india
Syntax:
function encodeQuery(data){
let query = ""
for (let d in data)
query += encodeURIComponent(d) + '=' +
encodeURIComponent(data[d]) + '&'
return query.slice(0, -1)
}
Below examples implements the above approach:
Example: To create a query parameters in JavaScript.
javascript
function encodeQuery(data) {
let query = ""
for (let d in data)
query += encodeURIComponent(d) + '='
+ encodeURIComponent(data[d]) + '&'
return query.slice(0, -1)
}
// Json object that should be
// converted to query parameter
data = {
'website': 'geeks',
'location': 'india'
}
queryParam = encodeQuery(data)
console.log(queryParam)
Outputwebsite=geeks&location=india
creating query parameters in JavaScript is a vital technique for passing data within URLs, enhancing the interactivity and functionality of web applications. By leveraging methods such as URLSearchParams, template literals, and custom functions, developers can efficiently generate and manage query strings, ensuring robust and dynamic web interactions.
Similar Reads
How to retrieve GET parameters from JavaScript ?
In order to know the parameters, those are passed by the âGETâ method, like sometimes we pass the Email-id, Password, and other details. For that purpose, We are using the following snippet of code. When you visit any website, ever thought about what the question mark '?' is doing in the address bar
2 min read
How to add a parameter to the URL in JavaScript ?
Given a URL the task is to add parameter (name & value) to the URL using JavaScript. URL.searchParams: This read-only property of the URL interface returns a URLSearchParams object providing access to the GET-decoded query arguments in the URL. Table of Content Using the append methodUsing set m
2 min read
How to Get Query Parameters from URL in Next.js?
In Next.js, getting query parameters from the URL involves extracting key-value pairs from the URL string to access specific data or parameters associated with a web page or application, aiding in dynamic content generation and customization. To get query parameters from the URL in next.js we have m
5 min read
How to Create JSON String in JavaScript?
JSON strings are widely used for data interchange between a server and a client, or between different parts of a software system. So converting objects to JSON strings is very important for good client-server communication. Below are the following approaches to creating a JSON string: Table of Conte
2 min read
How to get URL Parameters using JavaScript ?
To get URL parameters using JavaScript means extracting the query string values from a URL. URL parameters, found after the ? in a URL, pass data like search terms or user information. JavaScript can parse these parameters, allowing you to programmatically access or manipulate their values. For gett
3 min read
How to Pass Object as Parameter in JavaScript ?
We'll see how to Pass an object as a Parameter in JavaScript. We can pass objects as parameters to functions just like we do with any other data type. passing objects as parameters to functions allows us to manipulate their properties within the function. These are the following approaches: Table of
3 min read
How to concatenate regex literals in JavaScript ?
Regex is a sequence of pattern that is used for matching with a pattern. While searching for data in a text, the search pattern is described for what we are searching for. It can be a single character or a more complex pattern. It can be used to perform all types of text searches. Regex has its own
2 min read
How to declare the optional function parameters in JavaScript ?
Declaring optional function parameters in JavaScript means defining function parameters that aren't required when the function is called. You can assign default values to these parameters using the = syntax, so if no argument is provided, the default value is used instead. These are the following ap
3 min read
How to Create a Link in JavaScript ?
In JavaScript, a link typically refers to creating HTML hyperlinks (<a> tags) dynamically using JavaScript. You can link using a document.createElement('a'), setting attributes like href and textContent, and then appending it to the document with appendChild(). Here are some common approaches
4 min read
How to Create XML in JavaScript ?
In JavaScript, XML documents can be created using various approaches. You can define elements, attributes, and content to structure the XML data, and then serialize it into a string for use or storage. There are several approaches to creating XML in JavaScript which are as follows: Table of Content
2 min read