Programming

How to Modify URL Query Parameters in Node.js

In my previous post, I suggested that string concatenation is an unreliable way to modify URL queries. Let’s explore this idea a little further (or, just skip to the tl;dr if you just want the solution). First, let’s write a function that appends a URL query parameter via string concatenation:

Now, let’s throw some data at it to see what happens:

Hmm… that second output looks slightly invalid. URL query parameters are supposed to be delimited with “&” characters, not “?” characters. The correct output should have been:

How can we fix this? Well, one way would be to change the function’s behavior depending upon whether or not a “?” character was already present in the string. Let’s give it a try:

Dang! We fixed the previous case, but the approach still fails for URLs that contain the “#” fragment identifier. We could still probably solve the problem via string concatenation if we were smart about how we split the string beforehand. But, at this point, the approach just sounds way too complicated. :-/

Let’s just admit defeat and use Node’s url module instead:

It works! We’re officially #winning at life now!

Leave a Reply

Your email address will not be published. Required fields are marked *