Simplifies working with search parameters in URLs.
Instead of:
const url = new URL(window.location.href)
url.searchParams.set("hello", "world")
url.searchParams.set("test", "123")
window.location.href = url.toString()
you can do this:
urlParams
.set("hello", "world")
.set("test", "123")
or even this:
urlParams.setAll({
hello: "world",
test: 123
})
49 | 44 | 14 | 36 | 17 |
Using npm:
npm install @trosckey/url-params
Using yarn:
yarn add @trosckey/url-params
Methods delete, set and append returns this for
call chain. To get URL string you can use instance
property url or toString().
If first argument is not defined, window.location.href will be used.
urlParams('https://github.com')
.set('hello', 'world')
.append('hello', 'web')
.url // https://github.com?hello=world&hello=web
import { URLParams } from '@trosckey/url-params'
new URLParams('https://github.com')
.set('hello', 'world')
.get('hello') // "world"
import { urlParams } from '@trosckey/url-params'
urlParams('https://github.com')
.set('hello', 'world')
.get('hello') // "world"
creates instance on every call, uses window.location.href
import { urlParams } from '@trosckey/url-params'
// window.location.href = 'https://github.com'
urlParams
.set('hello', 'world')
.get('hello') // "world"
import {
URLParams,
urlParams
} from '@trosckey/url-params/dist/index.min.js'
// ...
new URLParams().url
// ...
urlParams().url
// ...
urlParams.url
saveSate(default false) - using window.history.pushState
instead of window.history.replaceState
replaces window.location.href if none
of methods above is not available
Returns url string
Sets value with the given key
urlParams('https://github.com')
.set('hello', 'world')
.set('hi', 'web')
.url // https://github.com?hello=world&hi=web
Sets many values from object
urlParams('https://github.com')
.setAll({
hello: "world",
hi: "web",
})
.url // https://github.com?hello=world&hi=web
Appends value with the given key
urlParams('https://github.com')
.append('hello', 'world')
.append('hello', 'there', true)
.url // https://github.com?hello=world&hello=there
Returns first searched item from left, otherwise null
urlParams('https://github.com?hello=world&hello=there')
.get('hello') // "world"
urlParams('https://github.com')
.get('hi') // null
Returns all values of query param in array
urlParams('https://github.com?hello=world&hello=there')
.getAll('hello') // ["world", "there"]
urlParams('https://github.com')
.getAll('hello') // []
Returns all query params in two-dimensional array
urlParams('https://github.com?hello=world&hello=there&test=123')
.getAllParams() // [["hello", "world"], ["hello", "there"], ["test", "123"]]
Deleting query param from url
urlParams('https://github.com?hello=world')
.delete('hello')
.url // https://github.com
Returns url string, can be used for auto cast to string