Utils (@pim.sk/utils)

classUrl

URL parser and manipulator built on the native URL API. If no URL is provided, document.location.href (current browser URL) is used as default.
import classUrl from '@pim.sk/utils/class-url.mjs'

Usage

new classUrl(url)

Parse a URL and access its location properties.

const url  = "https://example.com/shop/products?page=2&sort=asc#top"
const curl = new classUrl(url)
output = curl.location

.aPath

Get path segments as an array.

'https://example.com/shop/products/list'
const paths = curl.aPath

.aQuery

Get query parameters as an object.

'https://example.com/page?a=1&b=two'
const query = curl.aQuery

.dirname / .basename

Get directory and filename from the URL path.

'https://example.com/shop/products/detail.php'
const dir  = curl.dirname
const base = curl.basename

.pathname (setter)

Change the pathname of the URL.

'https://example.com/shop/products'
curl.pathname = "shop/orders/new"

.addQuery (setter)

Add or update query parameters (string or object).

'https://example.com/page?a=1'
curl.addQuery = "b=2&c=three"

.removeQuery (setter)

Remove query parameters by key (comma-separated or array).

'https://example.com/page?a=1&b=2&c=3'
curl.removeQuery = "a,c"

.hash (getter / setter)

Get or set the URL hash (without #).

'https://example.com/page#section2'
const h = curl.hash   // get
curl.hash = "top"     // set

History

Working with browser history and manipulating URL addresses without reload the page.

.addHistoryPush(name, values, path)

Change the browser URL and write a new entry to the history stack (back button will return to previous URL).

name = "MyPage"
path = "shop/orders/new"
const curl = new classUrl()
curl.addHistoryPush("MyPage", null, "shop/orders/new")

.addHistoryReplace(name, values, path)

Change the browser URL and REPLACE the current history entry (back button will NOT return to previous URL).

name = "MyPage"
path = "shop/orders/detail"
const curl = new classUrl()
curl.addHistoryReplace("MyPage", null, "shop/orders/detail")

.addHistoryBack(fn)

Register a listener for the browser back/forward button. Callback receives event.state (query params at the time of push).

fn = (state) => { ... }
const curl = new classUrl()
curl.addHistoryBack((state, values, event) => {
    console.log("back:", state)
})
v 1.1.2