CyrefJS
CCyrefJS
فا
Back to documentation
URL/Since 1.38.0

setQueryParam

Sets or replaces a query parameter in a URL or query string while preserving the hash fragment.

setQueryParam(url, key, value):string

Behavior

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

urlstringrequired

The URL, query string, or URL-like string to modify.

keystringrequired

The name of the query parameter to set.

valuestringrequired

The string value to assign to the query parameter.

Returns

string

Returns the modified URL or query string with the specified parameter set and the hash fragment preserved.

Examples

01

Add a parameter

Add a new query parameter to a URL.

TypeScript
import { setQueryParam } from "@cyref/js";

setQueryParam(
  "https://example.com/products",
  "page",
  "2",
);
// "https://example.com/products?page=2"
02

Replace a parameter

Replace the value of an existing query parameter.

TypeScript
setQueryParam(
  "https://example.com/products?page=1&sort=latest",
  "page",
  "2",
);
// "https://example.com/products?page=2&sort=latest"
03

Preserve hash

The hash fragment remains unchanged when setting a query parameter.

TypeScript
setQueryParam(
  "https://example.com/products?page=1#details",
  "page",
  "2",
);
// "https://example.com/products?page=2#details"
04

Query string input

A query string can be passed directly without a URL path.

TypeScript
setQueryParam(
  "?page=1&sort=latest",
  "page",
  "2",
);
// "?page=2&sort=latest"
05

URL encoding

The parameter value is serialized according to URLSearchParams behavior.

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