1.38.0removeQueryParam
Removes a specific query parameter from a URL or query string while preserving the hash fragment.
removeQueryParam(url, key):stringHash Preservation
The function separates the hash fragment before processing the query and appends it to the returned result unchanged.
Query Processing
The query portion is parsed with URLSearchParams and the specified key is removed using delete().
URL and Query String Support
The function handles 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.
Empty Query
When removing the final query parameter, the question mark is removed instead of leaving an empty query string. The hash, if present, remains.
Duplicate Keys
All values associated with the specified key are removed by URLSearchParams.delete().
Parameters
urlstringrequiredThe URL, query string, or URL-like string from which the parameter should be removed.
keystringrequiredThe query parameter name to remove.
Returns
stringReturns the URL or query string with the specified parameter removed and the hash fragment preserved.
Examples
Remove a parameter from a URL
Remove a query parameter while keeping the rest of the URL unchanged.
import { removeQueryParam } from "@cyref/js";
removeQueryParam(
"https://example.com/products?page=2&sort=latest",
"page",
);
// "https://example.com/products?sort=latest"Remove the only parameter
When the removed parameter is the only query parameter, the question mark is removed as well.
removeQueryParam(
"https://example.com/products?page=2",
"page",
);
// "https://example.com/products"Preserve hash
The hash fragment is preserved when removing a query parameter.
removeQueryParam(
"https://example.com/products?page=2#details",
"page",
);
// "https://example.com/products#details"Query string input
A query string without a URL path can also be processed.
removeQueryParam("?page=2&sort=latest", "page");
// "?sort=latest"
removeQueryParam("?page=2", "page");
// ""Repeated parameters
All occurrences of the specified key are removed because URLSearchParams.delete() removes every value associated with that key.
removeQueryParam(
"https://example.com?tag=js&tag=ts&sort=latest",
"tag",
);
// "https://example.com?sort=latest"