Url
import { getQueryStringByName, queryStringMap, addQueryParams } from '@bbc/front-end-kit/js/utils/url';
This file contains utility functions for working with URLs and query strings in JavaScript.
getQueryStringByName
Gets the value of a query parameter by its name from a URL string or the current page URL.
Parameters
name(string): The name of the query parameter to retrieve.url(string, optional): The URL string to search for the query parameter. If not provided, defaults to the current page URL.
Returns
string|null: The value of the query parameter, or null if the parameter is not found in the URL.
Example
import { getQueryStringByName } from '@bbc/front-end-kit/js/utils/url';
// If the URL is "https://example.com/?id=123&name=John"
getQueryStringByName("id"); // returns "123"
getQueryStringByName("name"); // returns "John"
queryStringMap
Parses a URL's query string parameters into an object.
Parameters
url(string, optional): The URL string to parse. If not provided, defaults to the current page URL.
Returns
object: An object containing the query string parameters and their values.
Example
import { queryStringMap } from '@bbc/front-end-kit/js/utils/url';
// If the URL is "https://example.com/?id=123&name=John"
queryStringMap(); // returns { id: "123", name: "John" }
// If the URL is "https://example.com/page.html?id=123&name=John"
queryStringMap("https://example.com/page.html?id=123&name=John"); // returns { id: "123", name: "John" }
addQueryParams
Adds query string parameters to the given URL using the key-value pairs in the provided object map. If a parameter with the same key already exists in the URL, its value will be overwritten.
Parameters
url(string): The URL to add the query string parameters to.params(object): An object containing the key-value pairs to add to the query string.
Returns
string: The modified URL with the query string parameters added.
Example
import { addQueryParams } from '@bbc/front-end-kit/js/utils/url';
const url = "https://example.com/?id=123";
const params = { name: "John", id: "456" };
const newUrl = addQueryParams(url, params);
console.log(newUrl); // "https://example.com/?id=456&name=John"