Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Created November 30, 2018 17:24
Show Gist options
  • Save OliverJAsh/a97bdb3fa462df9785e9a5d8e78071ae to your computer and use it in GitHub Desktop.
Save OliverJAsh/a97bdb3fa462df9785e9a5d8e78071ae to your computer and use it in GitHub Desktop.

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.:

https://gist.github.com/ca8fafdbd2f53d59fcb7a21324c12900

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

https://gist.github.com/59cfe2f0c1b9c684c9e988cd3e104ef0

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:

https://gist.github.com/c57e89e7a3e1496001d7405cdcf83868

For example, here's a addQueryToUrl transformer which uses mapUrl:

https://gist.github.com/ae3545c281ed49b1a1f18e5bc5ac733d

Here's what addQueryToUrl looks like in practice:

https://gist.github.com/4c2ca9c6f9aa624b6380ea06ed805a08

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment