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=newyorkIn this URL, we have three parameters:
- name with value john
- age with value 25
- city with value newyork
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 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.

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.

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); // 25Real-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:
- jQuery Replace Text in String
- jQuery Drag and Drop File Upload
- jQuery Get ID of Clicked Element
- jQuery Remove All Options from Select

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.