Unsplash Blog
Published in

Unsplash Blog

Manipulating URL strings with `url-transformers`

At Unsplash we’ve just published , a small helper library for manipulating URL strings in Node and in the browser. provides several functions for common URL transformations, such as adding a search/query string to a URL or appending to the URL pathname.

Currently provides the following (hopefully self-explanatory) helpers:

There are many more possibilities, so we would love for you to help us grow this collection!

In this article we’ll explain why you we decided to build these helpers using Node’s URL parser instead of string manipulation.

URL transformations are most often achieved using simple string manipulation, e.g.:

However, these naive functions are quickly swamped by edge cases. For example:

Instead of manipulating the URL as a string, we can parse the URL to an object using Node’s URL parser. Once we’ve parsed the URL, we can manipulate specific fields on the parsed URL object, which is much less error prone than manipulating a string. Once we’re done, we can stringify the parsed URL object to get back an old fashioned URL string.

Seeing as we have many different use cases for manipulating a URL, we can define a function that receives the URL as a string, parses it, maps the parsed URL object using the provided function, and then converts the URL back to a string:

For example, here’s a transformer which uses :

Here’s what looks like in practice:

The example above is very similar to the one that ships as part of , along with several other helpers.

If you like how we do things at Unsplash, consider joining us!



Behind the scenes building the open photography movement at Unsplash.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store