Introduction
In this lab, we will explore how to convert a string into a URL-friendly slug using JavaScript. The process involves normalizing the string by converting it to lowercase and removing special characters, followed by replacing spaces, dashes, and underscores with hyphens. By the end of this lab, you will have a function that can generate a slug from any given string, making it easier to use in URLs and other web-based applications.
Function to Convert String to URL Slug
To convert a string to a slug that can be used in a URL, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
String.prototype.toLowerCase()andString.prototype.trim()methods to normalize the string. - Use the
String.prototype.replace()method to replace spaces, dashes, and underscores with-, and remove special characters. - Implement the following code:
const slugify = (str) =>
str
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, "")
.replace(/[\s_-]+/g, "-")
.replace(/^-+|-+$/g, "");
- Test the function with the input
slugify('Hello World!');and it should return the output'hello-world'.
Summary
Congratulations! You have completed the String to Slug lab. You can practice more labs in LabEx to improve your skills.