7 years ago, I wrote a post about how to get params from a URL via javascript. It used the RegExp() function, which isn't an elegant way, but worked fine to grab URL parameters.
Now there's a much better way to get, set, append and delete URL parameters in a URL.
Javascripts URL() constructor
You can get a breakdown of a URL's properties via the URL()
constructor.
// get the current URL in the browser
// and create a new URL() object
const url = new URL(window.location.href)
It will create an object with the following attributes.
hash: ""
host: "www.robkjohnson.com"
hostname: "www.robkjohnson.com"
href: "https://www.robkjohnson.com/"
origin: "https://www.robkjohnson.com"
password: ""
pathname: "/"
port: ""
protocol: "https:"
search: ""
searchParams: URLSearchParams {}
username: ""
One of the properties is called searchParams
which is an array that will contain all of the parameters in the url that is passed into the URL()
constructor.
You can use searchParams
to set, get, append and delete url parameters as needed.
// define the variables/value for your params
const size = 'L'
const color = 'red'
// set a param
url.searchParams.set('size', size) // adds ?size=L
url.searchParams.set('color', color) // adds &color=red
// get a param
url.searchParams.get('size') // L;
// append a param
url.searchParams.append('fabric', 'cotton') // adds &fabric=cotton at the end of the url
// delete a param
url.searchParams.delete('size') // deletes the size parameter
// transform the url object to a string
url.toString() // https://www.robkjohnson.com/?color=red&fabric=cotton