Get Query Parameters as Object
Retrieves URL query parameters and converts them into a standard JavaScript object with string keys and values.
Importβ
import { getQueryParams } from 'nhb-toolbox';
Function Signatureβ
function getQueryParams(): Record<string, string>
Usage Examplesβ
- Basic Usage
- No Query Parameters
- URL Encoded Values
// If the current URL is: https://example.com/?user=alex&role=admin
const params = getQueryParams();
// Returns: { user: "alex", role: "admin" }
// If the current URL is: https://example.com/
const params = getQueryParams();
// Returns: {}
// If the current URL is: https://example.com/?q=hello%20world
const params = getQueryParams();
// Returns: { q: "hello world" }
API Referenceβ
Parametersβ
Name | Type | Description |
---|---|---|
(none) | (none) | No arguments required; uses window.location.search |
Returnsβ
A plain object (Record<string, string>
) mapping query parameter names to their string values.
Key Featuresβ
- Automatic Extraction: Reads directly from the current URL without manual input.
- URL Decoding: Automatically decodes parameter values.
- Simple Interface: No configuration or arguments required.
Limitationsβ
- Browser-only: Requires a
window
environment. Not suitable for Node.js/server-side use. - Only First Values: If a key appears multiple times, only the last value is kept.
- String Values Only: All returned values are strings, not numbers or booleans.
- Single-level: Does not parse nested or structured parameters.
Notesβ
- Updating the URL (e.g., via History API) will affect the result on the next call.
- Empty query strings will return an empty object
{}
. - Keys and values are automatically decoded.
Recommended Use Casesβ
- Reading filters, search terms, or IDs from URLs in single-page applications.
- Prefilling form fields or search boxes based on current URL parameters.
- Logging or analytics of URL parameter usage.
Conclusion:
getQueryParams
is a lightweight utility for extracting URL query parameters in the browser. Itβs most useful for simple scenarios where you need a quick object view of the current URLβs query string.