JAVASCRIPT
Extract URL Query Parameters by Name
Learn to extract specific query parameters from a URL string in JavaScript using regular expressions, useful for parsing dynamic URLs.
const getQueryParam = (url, param) => {
param = param.replace(/[\[\]]/g, '\\$&'); // Escape special chars for regex
const regex = new RegExp(`[?&]${param}(=([^&#]*)|&|#|$)`, 'i');
const results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
};
const urlString = "http://example.com/path?name=John%20Doe&age=30&city=";
console.log(getQueryParam(urlString, "name")); // "John Doe"
console.log(getQueryParam(urlString, "age")); // "30"
console.log(getQueryParam(urlString, "city")); // ""
console.log(getQueryParam(urlString, "id")); // null
How it works: This function extracts the value of a specified query parameter from a URL string. It constructs a dynamic regular expression to find the parameter by name, accounting for its position (start, middle, or end of query string) and handles URL-encoded characters. It returns the decoded parameter value, an empty string if the parameter exists but has no value, or `null` if the parameter is not found.