Skip to content

Get URL parameters in JavaScript

Haikel Fazzani Haikel Fazzani
2024-11-03

Let’s break down getting URL parameters in JavaScript with some super simple examples and what you’d actually see in the console.

First, imagine the current URL in the browser is:

https://example.com/page?name=John&age=30&hobby=reading&hobby=gaming

We want to grab those name, age, and hobby bits.


This is the cleanest, most modern way. It’s built right into the browser for handling query strings.

Example Code:

// Get the current page's full URL
const currentUrl = new URL(window.location.href);
console.log("Current URL Object:", currentUrl);

// Get the search parameters part
const searchParams = currentUrl.searchParams;
console.log("SearchParams Object:", searchParams);

// --- Get a single value ---
const name = searchParams.get('name');
console.log("Name:", name); // Output: John

// --- Get ALL values for a key (like 'hobby') ---
const hobbies = searchParams.getAll('hobby');
console.log("Hobbies:", hobbies); // Output: ['reading', 'gaming']

// --- Check if a parameter exists ---
const hasAge = searchParams.has('age');
console.log("Has Age?", hasAge); // Output: true

// --- Loop through all parameters ---
console.log("--- All Parameters ---");
for (const [key, value] of searchParams) {
  console.log(`${key}: ${value}`);
}
// Output:
// name: John
// age: 30
// hobby: reading
// hobby: gaming

// --- Get all keys ---
console.log("--- All Keys ---");
for (const key of searchParams.keys()) {
  console.log(key);
}
// Output:
// name
// age
// hobby
// hobby

// --- Get all values ---
console.log("--- All Values ---");
for (const value of searchParams.values()) {
  console.log(value);
}
// Output:
// John
// 30
// reading
// gaming

2. Using window.location.search with URLSearchParams

Sometimes you just need the query string part (?name=...) and feed it directly to URLSearchParams. This is essentially the same as method 1 but broken into steps.

Example Code:

// Get just the query string part (e.g., "?name=John&age=30...")
const queryString = window.location.search;
console.log("Raw Query String:", queryString); // Output: ?name=John&age=30&hobby=reading&hobby=gaming

// Parse it with URLSearchParams
const params = new URLSearchParams(queryString);
console.log("Parsed Params:", params);

// Get a value
const age = params.get('age');
console.log("Age:", age); // Output: 30

// Get all values for 'hobby'
const hobbiesAgain = params.getAll('hobby');
console.log("Hobbies (again):", hobbiesAgain); // Output: ['reading', 'gaming']

3. Using Regular Expressions (For Complex Cases or Learning)

This is more complex but gives you full control. It’s good to understand, but URLSearchParams is usually better.

Example Code:

const queryString = window.location.search; // "?name=John&age=30&hobby=reading&hobby=gaming"
console.log("Raw Query String:", queryString);

// Our results object
const paramsObj = {};

// The regex: finds key=value pairs
const regex = /([^&=?]+)=?([^&]*)/g;

let match;
// Loop through all matches
while (match = regex.exec(queryString)) {
  // match[1] is the key, match[2] is the value
  // decodeURIComponent handles special characters like %20 for spaces
  const key = decodeURIComponent(match[1]);
  const value = decodeURIComponent(match[2]);

  // Handle multiple values for the same key (like hobby)
  if (paramsObj[key]) {
    // If key exists, make it an array or push to existing array
    if (Array.isArray(paramsObj[key])) {
      paramsObj[key].push(value);
    } else {
      paramsObj[key] = [paramsObj[key], value];
    }
  } else {
    // If key doesn't exist, just set the value
    paramsObj[key] = value;
  }
}

console.log("Params Object (via Regex):", paramsObj);
// Output: { name: 'John', age: '30', hobby: ['reading', 'gaming'] }

// Accessing values
console.log("Name (regex):", paramsObj.name); // Output: John
console.log("Hobbies (regex):", paramsObj.hobby); // Output: ['reading', 'gaming']

4. Using jQuery (Legacy or Existing jQuery Projects)

Important Note: jQuery does not have a built-in $.urlParam function. The blog post example is incorrect. You would need to define it yourself or use a plugin.

Here’s how you could define a simple $.urlParam function using URLSearchParams (assuming jQuery $ is available and window.location.search is used):

Example Code:

// Define a custom jQuery-like function (this is NOT built-in)
$.urlParam = function(name){
    // Use URLSearchParams on the current window's search string
    const results = new URLSearchParams(window.location.search);
    // Return the value for 'name', or null if not found
    return results.get(name) || null;
};

// --- Use the custom function ---
const nameFromJq = $.urlParam('name');
console.log("Name (via custom jQuery fn):", nameFromJq); // Output: John

const nonExistent = $.urlParam('city');
console.log("City (via custom jQuery fn):", nonExistent); // Output: null

// To get ALL values, you'd need a different custom function:
$.urlParamAll = function(name) {
    const results = new URLSearchParams(window.location.search);
    return results.getAll(name);
}

const hobbiesFromJq = $.urlParamAll('hobby');
console.log("Hobbies (via custom jQuery fn):", hobbiesFromJq); // Output: ['reading', 'gaming']

(Remember, you need to include the jQuery library <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> for $ to work, and you must define $.urlParam yourself as shown.)


5. Polyfills for Older Browsers

If you must support very old browsers that don’t have URLSearchParams, you’d include a polyfill library (like the one mentioned) before your code runs. Then, you can use new URLSearchParams(...) just like in methods 1 and 2, and the polyfill fills in the gaps. The code looks identical to the examples above; the polyfill just makes it work where it wouldn’t normally.


Conclusion:

For modern web development, stick with Method 1 or 2 using URLSearchParams. It’s simple, standard, and powerful. Regular expressions are powerful but usually overkill for basic parameter parsing. jQuery doesn’t have a native solution, so you’d need custom code or a plugin, making the native API the better choice if you’re not already deep in a jQuery project.

nodejs URLSearchParams URL.keys object javascript

More Insights.