Skip to main content

Read URL search parameters with JavaScript

Search parameters, or query strings, are handy ways to store data on URLs. JavaScript provides an interface for reading search parameters called URLSearchParams. To use it, create an instance with the new keyword and pass your search parameter string as an argument:

let params = "?name=Sam&name=Ezra";
let usp = new URLSearchParams(params);

The returned URLSearchParams object has a few a bunch of useful methods, but we’re going to focus on three:

If I call the get() method for name, then it will return the first value from my search parameter string:

usp.get("name");
// 'Sam'

When you are dealing with unique parameters, this method is all you need to get the job done. But in our example, there are multiple names being passed. To retrieve all of those values, we will call getAll() with name:

usp.getAll("name");
// ['Sam', 'Ezra']

If you are working with a few exact keys, you can probably stop there. But if you are dealing with a lot of keys or just want an easier way to read search parameters, you can use a helper function that iterates over all of the keys and stores them in an object:

/**
 * Read the search parameters from window location
 */
function readSearchParams() {
  let usp = new URLSearchParams(window.location.search);
  let params = {};
  usp.forEach((value, key) => {
    if (!params[key]) {
      params[key] = [];
    }
    params[key].push(value);
  });
  return params;
}

Then call the function whenever you need to reference the current location’s search parameters:

// https://seanmcp.com/articles/read-url-search-parameters-with-javascript/
// ?greeting=Hello&name=World
let params = readSearchParams();

params.greeting;
// ['Hello']
params.name;
//['World']

To see it in action, try going to that url, or try adding your own search parameters.

Happy reading!



About the author

Sean McPherson is a software engineer for Khan Academy who specializes in web and mobile app development. He lives with his wife, sons, and dog in Pittsburgh, PA.