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
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read