1.38.0buildQuery
Builds a URL query string from a record of string key-value pairs.
buildQuery(params):stringBehavior
The function creates a URLSearchParams instance from the provided record and returns its serialized string representation using toString().
URL Encoding
Parameter names and values are serialized according to the behavior of URLSearchParams, including URL encoding of special characters.
Query String Format
The returned string contains key-value pairs separated by ampersands and does not include a leading question mark.
Parameters
paramsRecord<string, string>requiredAn object containing string keys and string values to convert into URL query parameters.
Returns
stringReturns the encoded query string without a leading question mark.
Examples
Basic usage
Build a query string from key-value pairs.
import { buildQuery } from "@cyref/js";
buildQuery({
page: "2",
limit: "10",
});
// "page=2&limit=10"URL encoding
Special characters and spaces are encoded according to URLSearchParams.
buildQuery({
search: "hello world",
category: "web development",
});
// "search=hello+world&category=web+development"Using the result in a URL
The returned query string can be appended to a URL using a question mark.
const query = buildQuery({
page: "1",
sort: "latest",
});
const url = `https://example.com/posts?${query}`;
// "https://example.com/posts?page=1&sort=latest"