Skip to Content

How To Slugify A String with JavaScript

In this tutorial, you'll learn how to slugify a string with JavaScript. Slugify means simply converting any text string into a URL-friendly URL.

What Is A Slug?

A slug is a unique identifier of a web address, typically at the end or after the domain name. Each slug should be unique to distinguish different parts of a website without duplication.

Here's an example:

https://orangeable.com/slug-here

The slug is slug-here comes after the domain name and at the end of the URL string.

Slugs should only contain alpha-numeric characters and - dashes. Spaces, underscores, and any other special characters should be removed from slugs. They should be short and easy to remember so users can easily navigate back to a page they need to reference.

How To Slugify A String

To convert a string to a slug, we'll use JavaScript's String.prototype.toLowerCase() and String.prototype.trim() methods to normalize the string and String.prototype.replace() to replace any existing spaces or special characters with - dashes using regular expressions.

function slugify(str) {
return str
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, "")
.replace(/[\s_-]+/g, "-")
.replace(/^-+|-+$/g, "");
}

var new_str = slugify("Hello There!");

console.log(new_str);
// hello-there

As you can see, a custom slugify() function is created, taking our referenced string and running it through the built-in JavaScript functions to reshape the text string into a slug.

Conclusion

This tutorial taught you how to convert a standard string into a URL-friendly slug for website navigation.

If you're not sure about the methods used, you can read more about string replacements and regular expressions here.

Or let me know if you have any questions in the comments below!

Created: January 11, 2023

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.