Query parameters also referred to as URL parameters is a pair of key-value that is put on the edge of a URL to assist. Hence, they are popularly used by web pages to pass info via URL. It is crucial for web developers who want to fetch & edit them on live basis in JS to handle requests containing URL parameters. In the following blog post, we will walk through some helpful strategies and tips through which you can effectively deal with URL parameters in JavaScript.

Using URLSearchParams API

// Assuming URL: https://example.com/page?name=John&age=30

const urlParams = new URLSearchParams(window.location.search);

// Get individual parameter values
const name = urlParams.get('name'); // Returns 'John'
const age = urlParams.get('age'); // Returns '30'

// Add a new parameter
urlParams.append('city', 'New York');

// Convert back to string with updated parameters
const newUrl = `${window.location.origin}${window.location.pathname}?${urlParams.toString()}`;
console.log(newUrl); // Outputs: https://example.com/page?name=John&age=30&city=New%20York

Parsing Manually with JavaScript

For environments without URLSearchParams support, parsing can be done manually using JavaScript string and array methods.

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

// Usage
const name = getParameterByName('name');
const age = getParameterByName('age');

Framework-Specific Methods

Frameworks like React, Angular, or Vue.js often provide their own utilities or methods for handling URL parameters, leveraging their routing capabilities.

import { useLocation } from 'react-router-dom';

function Component() {
    const searchParams = new URLSearchParams(useLocation().search);
    const name = searchParams.get('name');
    const age = searchParams.get('age');

    // Use name and age here
}

Security Considerations

When you are dealing with URL parameters, remember that there are security threats such as XSS (Cross-Site Scripting) attacks which could affect your system so you have to always sanitize and validate any parameter that comes into your system before it is used because it is the surest way of avoiding these incidents.

Categorized in:

JavaScript,

Last Update: July 27, 2024