Manipulating URL strings with `url-transformers`
At Unsplash we’ve just published url-transformers
, a small helper library for manipulating URL strings in Node and in the browser. url-transformers
provides several functions for common URL transformations, such as adding a search/query string to a URL or appending to the URL pathname.
Currently url-transformers
provides the following (hopefully self-explanatory) helpers:
addQueryToUrl
replacePathInUrl
replacePathnameInUrl
appendPathnameToUrl
replaceHashInUrl
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.
mapUrl
Seeing as we have many different use cases for manipulating a URL, we can define a mapUrl
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 addQueryToUrl
transformer which uses mapUrl
:
Here’s what addQueryToUrl
looks like in practice:
The example addQueryToUrl
above is very similar to the one that ships as part of url-transformers
, along with several other helpers.
If you like how we do things at Unsplash, consider joining us!