JAVASCRIPT

Extract Specific Query Parameters from a URL

Discover how to use regular expressions in JavaScript to efficiently extract individual query parameters and their values from a URL string.

function getQueryParam(url, param) {
  param = param.replace(/[\[\]]/g, '\\$&'); // Escape special chars for regex
  const regex = new RegExp('[?&]' + param + '(=([^&#]*)|&|#|$)');
  const results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

// Examples:
// const url = "https://www.example.com/search?q=regex+patterns&page=2&sort=asc";
// console.log(getQueryParam(url, 'q'));    // "regex patterns"
// console.log(getQueryParam(url, 'page')); // "2"
// console.log(getQueryParam(url, 'sort')); // "asc"
// console.log(getQueryParam(url, 'nonexistent')); // null
How it works: This JavaScript function takes a URL string and a parameter name, using a regular expression to find and extract the value of that specific query parameter. It correctly handles URL encoding and ensures that special characters in the parameter name are properly escaped to prevent regex errors.

Need help integrating this into your project?

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

Hire DigitalCodeLabs