Parse query string in JavaScript

Learn parse query string in javascript with practical examples, diagrams, and best practices. Covers javascript, parsing, query-string development techniques with visual explanations.

Mastering Query String Parsing in JavaScript

Hero image for Parse query string in JavaScript

Learn various techniques to effectively parse and extract data from URL query strings in JavaScript, from native browser APIs to custom solutions.

Query strings are a fundamental part of web development, allowing data to be passed between pages or to a server. They typically appear after a URL's path, starting with a question mark (?), and consist of key-value pairs separated by ampersands (&). Understanding how to parse these strings in JavaScript is crucial for building dynamic and interactive web applications. This article will guide you through several methods, from modern browser APIs to more traditional approaches, helping you choose the best solution for your needs.

Understanding Query String Structure

Before diving into parsing methods, it's important to recognize the common structure of a query string. A typical URL with a query string looks like this:

https://example.com/search?query=javascript&page=2&sort=asc

Here, query=javascript, page=2, and sort=asc are the key-value pairs. Each key is separated from its value by an equals sign (=), and each pair is separated from the next by an ampersand (&). Values are often URL-encoded, meaning special characters are converted into a format that can be safely transmitted over the internet (e.g., spaces become %20).

flowchart TD
    A[URL] --> B{Path}
    A --> C{Query String}
    C --> D[Key-Value Pair 1]
    C --> E[Key-Value Pair 2]
    C --> F[...]
    D -- "Key = Value" --> G[Parameter]
    E -- "Key = Value" --> H[Parameter]
    G & H -- "Separated by &" --> C

Basic structure of a URL with a query string.

Method 1: Using URLSearchParams (Modern Browsers)

The URLSearchParams interface is the most robust and recommended way to handle query strings in modern browsers and Node.js environments. It provides a convenient API for working with the query string of a URL, including parsing, adding, deleting, and iterating over parameters. It automatically handles URL encoding and decoding, making it highly reliable.

// Example URL
const url = 'https://example.com/products?category=electronics&price_range=100-500&sort=asc&page=3';

// Get the query string part of the URL
const queryString = url.split('?')[1];

// Create a URLSearchParams object
const params = new URLSearchParams(queryString);

// Access individual parameters
console.log(params.get('category'));      // Output: electronics
console.log(params.get('price_range'));   // Output: 100-500
console.log(params.get('sort'));          // Output: asc
console.log(params.get('page'));          // Output: 3

// Check if a parameter exists
console.log(params.has('category'));      // Output: true
console.log(params.has('color'));         // Output: false

// Iterate over all parameters
for (const [key, value] of params.entries()) {
  console.log(`${key}: ${value}`);
}
/* Output:
category: electronics
price_range: 100-500
sort: asc
page: 3
*/

// Handling multiple values for the same key
const multiValueUrl = 'https://example.com/search?tag=js&tag=web&tag=frontend';
const multiParams = new URLSearchParams(multiValueUrl.split('?')[1]);
console.log(multiParams.getAll('tag')); // Output: ["js", "web", "frontend"]

Using URLSearchParams to parse and access query parameters.

Method 2: Manual Parsing with String Methods and Regular Expressions

While URLSearchParams is preferred, you might encounter scenarios where you need to support older browsers or prefer a more manual approach for specific use cases. This method involves using string manipulation functions like split() and potentially regular expressions to extract the key-value pairs.

function parseQueryStringManually(queryString) {
  const params = {};
  if (!queryString) {
    return params;
  }

  // Remove leading '?' if present
  const cleanQueryString = queryString.startsWith('?') ? queryString.substring(1) : queryString;

  cleanQueryString.split('&').forEach(pair => {
    const parts = pair.split('=');
    if (parts.length === 2) {
      const key = decodeURIComponent(parts[0].replace(/\+/g, ' ')); // Handle '+' as space
      const value = decodeURIComponent(parts[1].replace(/\+/g, ' '));
      
      // Handle multiple values for the same key (simple array)
      if (params[key]) {
        if (Array.isArray(params[key])) {
          params[key].push(value);
        } else {
          params[key] = [params[key], value];
        }
      } else {
        params[key] = value;
      }
    } else if (parts.length === 1 && parts[0]) {
      // Handle keys without values (e.g., ?debug)
      params[decodeURIComponent(parts[0].replace(/\+/g, ' '))] = '';
    }
  });
  return params;
}

const url1 = 'https://example.com/page?name=John%20Doe&age=30&city=New+York';
const url2 = 'https://example.com/search?q=test&category=books&category=fiction';
const url3 = 'https://example.com/debug?mode';

console.log('URL 1:', parseQueryStringManually(url1.split('?')[1]));
/* Output:
URL 1: { name: 'John Doe', age: '30', city: 'New York' }
*/

console.log('URL 2:', parseQueryStringManually(url2.split('?')[1]));
/* Output:
URL 2: { q: 'test', category: [ 'books', 'fiction' ] }
*/

console.log('URL 3:', parseQueryStringManually(url3.split('?')[1]));
/* Output:
URL 3: { mode: '' }
*/

A custom function for parsing query strings using string manipulation.

Choosing the Right Method

The choice of method largely depends on your project's requirements and target browser support:

  • URLSearchParams: This is the recommended approach for most modern web development. It's robust, handles encoding/decoding automatically, and provides a clean API. It's supported in all major modern browsers and Node.js.
  • Manual Parsing: Consider this only if you need to support very old browsers (e.g., Internet Explorer 11 or older) that do not have URLSearchParams. For such cases, you might also consider using a polyfill for URLSearchParams or a well-tested third-party library.

1. Identify the Query String

First, extract the query string part of the URL. For the current page, use window.location.search. For a given URL string, split it by ? and take the second part.

2. Choose Your Parsing Method

Decide between URLSearchParams for modern environments or a custom string manipulation function for broader (older) browser compatibility.

3. Access Parameters

Use params.get('key') with URLSearchParams or access properties directly from your parsed object (e.g., parsedParams.key) for manual methods.

4. Handle Encoding/Decoding

If using manual parsing, ensure you correctly use decodeURIComponent() for both keys and values to handle URL-encoded characters.