How to get URL parameters with JavaScript

How to get URL parameters with JavaScript

Photo by Joshua Coleman

So let’s imagine you’re working with an app that has various different parameters added to the URL when loading data for example.

You might want to retrieve the various parameters to use in your JavaScript code.

The ​window.location.search ​property gives you everything in the search request but it’s a long string which makes it a bit difficult to pick out an individual parameter.

// Browsing: https://someurl.com/?search=abcd&user=1234
window.location.search; // ?search=abcd&user=1234

One thing you might want to do is parse the search string by using a URLSearchParams​object to parse it.

// Browsing: https://someurl.com/?search=abcd&user=1234
const​ params ​=​ ​new​ ​URLSearchParams​(​window​.​location​.​search​); 
p​arams.​get​(​'user'​);​ ​// 1234

You can then call the ​get ​function to retrieve any specific parameter you need.

Alternatively, you can reduce all of the keys in the ​URLSearchParms object to a single object.

// https://someurl.com/?search=abcd&user=1234
const​ params ​=​ ​new​ ​URLSearchParams​(​window​.​location​.​search​);
const​ searchParams ​=​ Array​.​from​(​p​arams.​keys​())
​  .​reduce​((​acc​,​ key​)​ ​=>​ ​({​ ​...​acc​,​ ​[​key​]​:​ p​.​get​(​key​)​ ​}), {});
// { search: 'abcd', user: '1234' }

Watch the tutorial for more details

Follow me on Twitter for more tutorials 👍