Open In App

How to Create Query Parameters in JavaScript ?

Last Updated : 25 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

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);

Output
https://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.

const website = 'geeks';
const location = 'india';
const url = `https://example.com?website=${website}&location=${location}`;
console.log(url);

Output
https://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.

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);

Output
https://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.

const url = new URL('https://example.com');
url.searchParams.append('website', 'geeks');
url.searchParams.append('location', 'india');
console.log(url.toString());

Output
https://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.

const url = new URL('https://example.com?website=geeks');
url.searchParams.set('website', 'geeks');
url.searchParams.set('location', 'india');
console.log(url.toString());

Output
https://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.

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);

Output
https://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.

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)

Output
website=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.



Next Article

Similar Reads