1.38.0setQueryParam
Sets or replaces a query parameter in a URL or query string while preserving the hash fragment.
setQueryParam(url, key, value):stringBehavior
The function separates the hash fragment, parses the query with URLSearchParams, sets the specified key to the provided value, and then reconstructs the result.
Set or Replace
If the specified key already exists, URLSearchParams.set() replaces its value. If the key does not exist, a new parameter is added.
Hash Preservation
The hash fragment is extracted before query processing and appended to the final result unchanged.
URL and Query String Support
The function supports full URL-like strings as well as query strings. When there is no question mark and the input does not contain a slash, the input is treated directly as query data.
URL Encoding
Query serialization follows the native behavior of URLSearchParams, including encoding special characters in keys and values.
Parameters
urlstringrequiredThe URL, query string, or URL-like string to modify.
keystringrequiredThe name of the query parameter to set.
valuestringrequiredThe string value to assign to the query parameter.
Returns
stringReturns the modified URL or query string with the specified parameter set and the hash fragment preserved.
Examples
Add a parameter
Add a new query parameter to a URL.
import { setQueryParam } from "@cyref/js";
setQueryParam(
"https://example.com/products",
"page",
"2",
);
// "https://example.com/products?page=2"Replace a parameter
Replace the value of an existing query parameter.
setQueryParam(
"https://example.com/products?page=1&sort=latest",
"page",
"2",
);
// "https://example.com/products?page=2&sort=latest"Preserve hash
The hash fragment remains unchanged when setting a query parameter.
setQueryParam(
"https://example.com/products?page=1#details",
"page",
"2",
);
// "https://example.com/products?page=2#details"Query string input
A query string can be passed directly without a URL path.
setQueryParam(
"?page=1&sort=latest",
"page",
"2",
);
// "?page=2&sort=latest"URL encoding
The parameter value is serialized according to URLSearchParams behavior.
setQueryParam(
"https://example.com/search",
"q",
"hello world",
);
// "https://example.com/search?q=hello+world"