Published on October 18, 2023

Making URL Manipulation A Breeze With UFO: An In-Depth Guide

Making URL Manipulation A Breeze With UFO: An In-Depth Guide

Url manipulation like parsing, joining, and normalizing are incredibly common tasks in web development. UFO, a super friendly JavaScript library built by incredible team at UnJS, makes this once complex task into a breeze. Today, we will dig deeper into what UFO brings to the table.

Starting Off: Getting UFO Onboard 🚀

Installation is a breeze. You can use NPM or yarn or your preferred package manager:

npm install ufo

To make the features of UFO available in your project, import the desired utilities:

// Example using ES Modules
import { normalizeURL, joinURL } from 'ufo'

// Example using CommonJS
const { normalizeURL, joinURL } = require('ufo')

Now let's get to the real fun — exploring and understanding the extensive capabilities of UFO.

Touring the Mothership: UFO’s Feature-Rich API 🛸

Ensuring URL Conformity: NormalizeURL

The normalizeURL utility is your first mate in making sure your URLs are tamed and ready for use – by ensuring proper encoding and standardizing pathnames to always start with a slash. It also expertly preserves any provided protocol/host. This really comes in handy when you're ingesting URLs from external sources and need to be sure they adhere to the standard format.

Imagine we got a URL from a web form that reads 'localhost3000?query=hello world#new article'. Here's how you would normalize it.

normalizeURL('localhost3000?query=hello world#new article')
// Returns: 'localhost3000?query=hello%20world#new%20article'

This normalizes the URL by encoding the spaces present in the query and the hash.

Building Dynamic URL Paths: JoinURL

Concatenating strings to create URLs is a common sight in code bases. However, small mistakes can lead to broken links. The joinURL utility provides a safer and more elegant way to join URL parts. For instance, when building dynamic paths based on user data.

One use case could be constructing a link to a user's profile or resources associated with a user:

const username = "miyazaki"
joinURL('/users/profile', username, 'posts')
// Returns: '/users/profile/miyazaki/posts'

Gone are the concerns about missing or extra slashes wrecking the URL!

Breaking Down URLs: ParseURL

The parseURL utility is the perfect tool to deconstruct a URL into its components, giving you an object outline of all parts. An important tool when you have to manipulate or assess specific sections of a URL.

Let's say we have a URL for a product page 'http://mywebshop.com/products?category=electronics#featured'. We can parse it into its elements like this:

parseURL('http://mywebshop.com/products?category=electronics#featured')
/* Returns:
{
protocol: 'http:',
auth: '',
host: 'mywebshop.com',
pathname: '/products',
search: '?category=electronics',
hash: '#featured'
}
*/

This breakdown of the URL allows us to separately check the protocol, identify the host, see the path of the URL, and separately analyze the search queries and the hash.

Rebuilding URLs: StringifyParsedURL

After parsing and modifying your URL sections as needed, you often need to convert this parsed URL back into a URL string. stringifyParsedURL does exactly this and can greatly de-clutter your code:

const urlObject = parseURL('http://mywebshop.com/products?category=electronics#featured')
urlObject.pathname = '/gadgets'

stringifyParsedURL(urlObject)
// Returns: 'http://mywebshop.com/gadgets?category=electronics#featured'

Note how we used both parseURL and stringifyParsedURL to change the pathname from '/products' to '/gadgets' while keeping the rest of the URL intact. This is a common use case when you need to alter a specific part of a URL, without affecting the rest of the URL.

There are many additional functions in the UFO library such as withHttp, withHttps, withProtocol and withoutProtocol to expressly control the protocol of URLs, isEqual to compare two URLs regardless of trailing slashes or encoding, and isRelative to check if a path is relative — just to name a few!

Conclusion

UFO, although straightforward to use, is full of careful considerations and nuances that make it an invaluable piece of your web development toolbox. Its expressive and consistent API eliminates many of the treacherous aspects of URL handling, making your life much easier.

URL manipulation is something you'll face in nearly every web project — and having a trusty tool like UFO at your disposal can really make a difference. I hope this deep dive into UFO was helpful and encourages you to use UFO in your projects.

For further information or to peek through other features and functionalities, check out the full UFO documentation on npm.

Once you've taken UFO for a spin, you'll never want to go back to the old ways of URL manipulation!

Interested in LogSnag?

Get started right now for free!