A quick intro to using query strings in JS

Scott Hunt
principledminds
Published in
2 min readSep 6, 2018

If you haven’t worked much with query strings then I can confidently tell you that they aren’t so bad… as long as you don’t have to support Internet Explorer.

The other day I was working on a project in React where I was injecting query strings to communicate to a table filter on another page what parameters to include on load. The idea was pretty straightforward. However, what I didn’t know was that the URLSearchParms() interface (used for parsing query strings) that comes out-of-the-box in almost all browsers & node wasn’t supported by Internet Explorer 11, which makes IE the only browser that doesn’t support it. The fact that I didn’t get any helpful error messages from the browser made me decide to give this adventure with IE development a full ZERO stars.

Ok, now that I’ve vented let’s look at how to parse query strings.

The first example below is how you would use good ol’ URLSearchParams. It’s pretty straight forward. The second screenshot is how to use a package called query-string to achieve the same. The big difference, if you use query-string properly you’ll get cross-browser support that includes IE 11 etc.

1. URLSearchParams

Easy peasy. Just remember to import Node’s ‘url’ module so you can get access to the constructor. Here are some helpful resources:

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

https://nodejs.org/dist/latest-v8.x/docs/api/url.html

2. query-string

This is an npm package you can easily install with the below code. IF you want support for older browsers including IE 11, then you have to download version 5 of this package. This is what worked for me… no more blank IE screens :)

npm install query-string@5

3. Be a boss and build your own parser with regular expressions

Sorry, but definitely didn’t build my own parser just for this post but it may be a good exercise for you if you want to get into regular expressions.

Thanks for reading. If you learned something, please say thanks and share a round of applause or follow me or codenoobs… or both!

--

--