How to Get URL Parameters Using jQuery?

Getting URL parameters is a fundamental skill every web developer needs. Whether you’re building dynamic web applications or need to pass data between pages, extracting query parameters from URLs is essential.

This comprehensive guide will show you multiple methods to get URL parameters using jQuery and plain JavaScript.

What Are URL Parameters?

URL parameters (also called query parameters or query strings) are key-value pairs appended to a URL after the question mark (?). For example:

https://example.com/page?name=john&age=25&city=newyork

In this URL, we have three parameters:

Method 1: Modern JavaScript URLSearchParams API (Recommended)

The most reliable and modern approach uses the built-in URLSearchParams API:

function getUrlParameter(paramName) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(paramName);
}

// Usage examples
const userName = getUrlParameter('name');        // Returns: john
const userAge = getUrlParameter('age');          // Returns: 25
const userCity = getUrlParameter('city');        // Returns: newyork
const missing = getUrlParameter('country');      // Returns: null

console.log('User Name:', userName);
console.log('User Age:', userAge);

You can see the output in the screenshot below.

Get URL Parameters Using jQuery

Get All Parameters at Once

Retrieve all query parameters in one go by converting them into a key-value object.

function getAllUrlParameters() {
    const urlParams = new URLSearchParams(window.location.search);
    const params = {};

    for (const [key, value] of urlParams) {
        params[key] = value;
    }

    return params;
}

// Usage
const allParams = getAllUrlParameters();
console.log(allParams); // {name: "john", age: "25", city: "newyork"}

Method 2: jQuery Plugin Approach

Create a custom jQuery plugin for getting URL parameters:

$.urlParam = function(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

// Usage with jQuery
$(document).ready(function() {
    const name = $.urlParam('name');
    const age = $.urlParam('age');

    $('#user-info').html(`Hello ${name}, you are ${age} years old!`);
});

You can see the output in the screenshot below.

How to Get URL Parameters Using jQuery

Method 3: Regular Expression Method

For situations where you need broader browser support:

function getParameterByName(name, 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 productId = getParameterByName('product_id');
const category = getParameterByName('category');

You can see the output in the screenshot below.

How to Get URL Parameters jQuery

Method 4: Split and Parse Method

A simple approach using string manipulation:

function parseUrlParameters() {
    const params = {};
    const queryString = window.location.search.substring(1);
    const pairs = queryString.split('&');

    pairs.forEach(pair => {
        const [key, value] = pair.split('=');
        if (key) {
            params[decodeURIComponent(key)] = decodeURIComponent(value || '');
        }
    });

    return params;
}

// Usage
const params = parseUrlParameters();
console.log(params.name);    // john
console.log(params.age);     // 25

Real-World Examples

Let me explain to you the real-world examples of getting URL parameters using jQuery.

Example 1: Dynamic Content Loading

Use URL parameters to load specific product details or filter items dynamically on page load.

$(document).ready(function() {
    const productId = new URLSearchParams(window.location.search).get('id');
    const category = new URLSearchParams(window.location.search).get('category');

    if (productId) {
        // Load product details
        $.ajax({
            url: `/api/products/${productId}`,
            method: 'GET',
            success: function(data) {
                $('#product-details').html(data);
            }
        });
    }

    if (category) {
        // Filter products by category
        $(`.product-item:not([data-category="${category}"])`).hide();
    }
});

Example 2: Form Pre-filling

Automatically populate form fields using values fetched directly from URL query parameters.

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

    // Pre-fill form fields from URL parameters
    urlParams.forEach((value, key) => {
        const field = $(`#${key}`);
        if (field.length) {
            if (field.is(':checkbox') || field.is(':radio')) {
                field.prop('checked', value === 'true');
            } else {
                field.val(decodeURIComponent(value));
            }
        }
    });
}

$(document).ready(prefillForm);

Example 3: Pagination System

Control page navigation and load paginated data based on URL parameters like page and limit.

function setupPagination() {
    const currentPage = new URLSearchParams(window.location.search).get('page') || 1;
    const itemsPerPage = new URLSearchParams(window.location.search).get('limit') || 10;

    // Update pagination controls
    $('.pagination .current').text(currentPage);

    // Load page data
    loadPageData(currentPage, itemsPerPage);
}

function loadPageData(page, limit) {
    $.ajax({
        url: '/api/data',
        data: { page, limit },
        success: function(response) {
            $('#content').html(response.html);
            updatePaginationLinks(page, response.totalPages);
        }
    });
}

Best Practices and Tips

Here are the best practices and tips for getting URL parameters using jQuery.

1. Always Handle Missing Parameters

Ensure your code gracefully falls back to a default value when a URL parameter is absent.

const userId = new URLSearchParams(window.location.search).get('user_id') || 'guest';

2. Decode Special Characters

Always use decodeURIComponent() when dealing with parameter values that might contain special characters.

3. Validate Parameter Values

Confirm that extracted query values meet the expected criteria before using them in your application.

function getValidatedParameter(name, validator) {
    const value = new URLSearchParams(window.location.search).get(name);
    return validator(value) ? value : null;
}

// Usage
const page = getValidatedParameter('page', val => !isNaN(val) && val > 0);

4. Handle Arrays in URL Parameters

Easily retrieve multiple values passed under the same query key as an array using getAll().

// URL: ?colors=red&colors=blue&colors=green
function getParameterArray(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.getAll(name);
}

const colors = getParameterArray('colors'); // ['red', 'blue', 'green']

Browser Compatibility

The URLSearchParams API is supported in all modern browsers (Chrome 49+, Firefox 29+, Safari 10.1+, Edge 17+). For older browser support, use the regular expression method or include a polyfill.

Conclusion

Getting URL parameters in jQuery and JavaScript is easy with modern web APIs. The URLSearchParams approach is the most reliable and recommended method for new projects. Choose the method that best fits your browser support requirements and use case complexity.

Remember to always validate and sanitize URL parameters, especially when using them in database queries or displaying user-generated content. This ensures your application remains secure and functions correctly across different scenarios.

You may also like to read other jQuery articles:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.