← Back to all snippets
JAVASCRIPT

Extract Specific Query Parameter from URL

A JavaScript function to efficiently parse a specific query parameter's value from a given URL string using regular expressions.

function getQueryParameter(url, paramName) {
  // Create a regex to find the parameter name followed by '=' and then its value
  // The value is captured until '&' or end of string is encountered.
  const regex = new RegExp(`[?&]${paramName}=([^&#]*)`);
  const match = regex.exec(url);
  return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null;
}

// Example Usage:
const url1 = "http://example.com/path?id=123&name=test%20user";
console.log(getQueryParameter(url1, "id"));   // 123
console.log(getQueryParameter(url1, "name")); // test user
console.log(getQueryParameter(url1, "token"));// null

const url2 = "http://example.com/?q=hello+world";
console.log(getQueryParameter(url2, "q"));   // hello world
How it works: The `getQueryParameter` JavaScript function extracts the value of a specified query parameter from a given URL string. It constructs a regular expression dynamically to find `?paramName=value` or `&paramName=value`, captures the value, and then `decodeURIComponent` to handle URL-encoded characters.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs