1.38.0getQueryParam
Retrieves a query parameter value from a URL or query string.
getQueryParam(url, key):string | nullBehavior
The function searches for the first question mark in the input. If one exists, everything after it is treated as the query string. If no question mark exists, the entire input is treated as the query string.
Empty Query
If the extracted query string is empty, the function immediately returns null without creating a URLSearchParams instance.
URLSearchParams
The query string is parsed using URLSearchParams, and the requested key is retrieved with get(). This means URL query decoding and parameter parsing follow the native URLSearchParams behavior.
Return Value
The function returns the parameter value as a string, or null when the requested key does not exist.
Parameters
urlstringrequiredThe URL or query string containing the parameter.
keystringrequiredThe name of the query parameter to retrieve.
Returns
string | nullReturns the parameter value when the key exists; otherwise, returns null.
Examples
Basic usage
Retrieve a query parameter from a full URL.
import { getQueryParam } from "@cyref/js";
getQueryParam(
"https://example.com/products?page=2&limit=10",
"page",
);
// "2"
getQueryParam(
"https://example.com/products?page=2&limit=10",
"limit",
);
// "10"Missing parameter
Returns null when the requested parameter does not exist.
getQueryParam(
"https://example.com/products?page=2",
"sort",
);
// nullQuery string input
The function can also receive a query string directly.
getQueryParam("page=2&sort=latest", "page");
// "2"
getQueryParam("page=2&sort=latest", "sort");
// "latest"Encoded values
Parameter values are decoded according to URLSearchParams behavior.
getQueryParam(
"https://example.com/search?q=hello+world",
"q",
);
// "hello world"