JAVASCRIPT
Extract Specific Query Parameter from a URL String
Learn to efficiently extract the value of a specific query parameter from a URL string using a regular expression in JavaScript, useful for frontend and backend logic.
const getQueryParam = (url, paramName) => {
const regex = new RegExp(`[?&]${paramName}(=([^&#]*))?`);
const match = regex.exec(url);
return match ? decodeURIComponent(match[2] || "") : null;
};
const url = "https://example.com/page?id=123&name=John%20Doe&ref=&type=web";
console.log(getQueryParam(url, "id")); // "123"
console.log(getQueryParam(url, "name")); // "John Doe"
console.log(getQueryParam(url, "ref")); // ""
console.log(getQueryParam(url, "type")); // "web"
console.log(getQueryParam(url, "nonexistent")); // null
How it works: This JavaScript snippet provides a function `getQueryParam` to extract the value of a specified query parameter from a given URL string. It dynamically constructs a regular expression to find the parameter name followed by its value (or an empty string if no value is present). `decodeURIComponent` is then used to properly handle URL-encoded characters in the extracted value.