CyrefJS
CCyrefJS
فا
Back to documentation
URL/Since 1.38.0

getQueryParam

Retrieves a query parameter value from a URL or query string.

getQueryParam(url, key):string | null

Behavior

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

urlstringrequired

The URL or query string containing the parameter.

keystringrequired

The name of the query parameter to retrieve.

Returns

string | null

Returns the parameter value when the key exists; otherwise, returns null.

Examples

01

Basic usage

Retrieve a query parameter from a full URL.

TypeScript
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"
02

Missing parameter

Returns null when the requested parameter does not exist.

TypeScript
getQueryParam(
  "https://example.com/products?page=2",
  "sort",
);
// null
03

Query string input

The function can also receive a query string directly.

TypeScript
getQueryParam("page=2&sort=latest", "page");
// "2"

getQueryParam("page=2&sort=latest", "sort");
// "latest"
04

Encoded values

Parameter values are decoded according to URLSearchParams behavior.

TypeScript
getQueryParam(
  "https://example.com/search?q=hello+world",
  "q",
);
// "hello world"
Built with@cyref/js·Official documentation