Getting Url parameters can be tricky. I am sure I am not the only one that has used google to search for the perfect regular expression to help extract a parameter from a Url.
While learning and mastering Regular Expressions is probably the best in this case. You might not have the time to learn them and just need a nice fix that is neat and easy to understand.
The code below shows how this can easily be done using the URL API
You can read more about the ins and outs of this API by checking out the link below:
Reading through the MDN docs, youβll notice this API has two interfaces the URL interface
and the URLSearchParams interface
.
The URL interface
in this case allows us to parse our Url and returns an object that represents it.
Note that one of the keys in the object (searchParams) refers to the URLSearchParams interface
. This interface gives us methods that allow us to work with the query string in a Url.
You can read more about the query string here: Query string - Wikipedia
Also check out all the methods that URLSearchParams interface
provides here: URLSearchParams - Web APIs | MDN
In this case all we need to do is call URLSearchParams.get()
and pass it the parameter name we need, as a string. Feel free to play around further with this API. No need for an editor this can all be done from your browser console!
Now while this API is amazing! It does have one issue. It is not supported by IE.
MDN does suggest we use window.URL in this case. Strangely enough I tested it on IE 11 and it didn't work. The docs on MDN do not give much more detail on an alternative for IE, so if you have to support IE try using a poly-fill. I like the solution shown on JQUERY BY EXAMPLE
When using any of these cool Web APIs it is important to check for browser compatibility. In my case I needed this method for a dashboard project that I am building for a client and the client only uses chrome (luckily). This allowed me to utilize this API.
Hope this short article can help you on your next project!
Got questions? Feel free to reach out via the comments or my twitter
Ok! Now back to learning π¨πΏβπ»
Top comments (2)
Nice! Didn't know about that.
Previously I would split the url at the
?
and then split the second array element (the string containing the query string) at each&
(if it existed) and then split each new array element at the=
to get the parameter list.Of course I also found that on Stack Overflow a while ago. I definitely didn't invent that one.
Ya I used to do the same thing until I fell on this trick from... Stack Overflow haha
From there I went to MDN to understand the API more. Hopefully it gets support from IE at some point