A quick intro to using query strings in JS

Scott
Scott
Sep 6, 2018 · 2 min read

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.

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

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

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!

principledminds

Stories about tech, life, and whatever else comes to mind

Scott

Written by

Scott

Software Developer, Former Stock Trader, Passionate Learner.

principledminds

Stories about tech, life, and whatever else comes to mind

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade