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 create object properties in JavaScript ?
JavaScript is built on an object-oriented framework. An object is a collection of properties, where each property links a key to a value. These properties are not in any specific order. The value of a JavaScript property can be a method (function). Object properties can be updated, modified, added,
4 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 mu
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 getti
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 Use Query Parameters in NestJS?
NestJS is a popular framework for building scalable server-side applications using Node.js. It is built on top of TypeScript and offers a powerful yet simple way to create and manage APIs. One of the core features of any web framework is handling query parameters, which allow developers to pass data
6 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
JavaScript Function Parameters
Function parameters are variables defined in the function declaration that receive values (arguments) when the function is called. They play a key role in making functions reusable and dynamic.Values are assigned to parameters in the order they are passed.You can assign default values to parameters
2 min read