🟨 JavaScript
Medium
🕐 15 min

Parse URL Parameters

Goal: create a function getUrlParams(url) that takes a URL string and returns an object containing all its GET parameters as key-value pairs.

💡 Hint
  1. The browser has built-in objects for working with URLs.
  2. Remember to decode special characters (e.g., %20 should become a space).
👀 Solution #1 (modern, using URLSearchParams)
function getUrlParams(url) {
  // Create a URL instance to easily access searchParams
  const searchParams = new URL(url).searchParams;
  // Convert the URLSearchParams iterator to an object
  return Object.fromEntries(searchParams.entries());
}

Why this way:

  • Reliable: Uses the built-in browser API, which correctly handles most edge cases (e.g., character encoding).
  • Readable: The code is short and clearly expresses its intent.
  • Modern: This is the standard way to work with URLs in modern JavaScript.
👀 Solution #2 (manual parsing)
function getUrlParams(url) {
  const params = {};
  const urlParts = url.split('?');
  
  if (urlParts.length > 1) {
    const queryString = urlParts[1];
    const pairs = queryString.split('&');
    
    for (const pair of pairs) {
      // Handle cases where a key exists without a value (e.g., ?a&b=2)
      const [key, value] = pair.split('=');
      if (key) {
        // decodeURIComponent to decode, e.g., %20 into a space
        params[decodeURIComponent(key)] = decodeURIComponent(value || '');
      }
    }
  }
  
  return params;
}

Why this way:

  • Educational: Helps to understand how URL strings work “under the hood”.
  • Flexible: Gives full control over the process if custom logic is needed.
  • No dependencies: Requires no special APIs, works with pure JavaScript.

Task Description

Write a function getUrlParams that takes a URL string as input and returns an object where the keys are the names of the GET parameters and the values are their values.

Examples

getUrlParams('https://example.com?a=1&b=hello'); // { a: '1', b: 'hello' }
getUrlParams('https://example.com?search=what%20is%20this'); // { search: 'what is this' }
getUrlParams('https://example.com'); // {}

Requirements

  • The function must be named getUrlParams.
  • If there are no parameters, the function should return an empty object.
  • Parameter values must be decoded (e.g., %20 should become a space).

🧑‍💻 It's not a bug! It's a feature!

The code editor is intentionally hidden on mobile.

Believe me, it's for the best: I am protecting you from the temptation to code in less-than-ideal conditions. A small screen and a virtual keyboard are not the best tools for a programmer.

📖 Now: Study the task, think through the solution. Act like a strategist.

💻 Later: Sit down at your computer, open the site, and implement all your ideas comfortably. Act like a code-jedi!