Creating URL-Friendly Slugs with JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28627{{"`Creating URL-Friendly Slugs with JavaScript`"}} javascript/data_types -.-> lab-28627{{"`Creating URL-Friendly Slugs with JavaScript`"}} javascript/arith_ops -.-> lab-28627{{"`Creating URL-Friendly Slugs with JavaScript`"}} javascript/comp_ops -.-> lab-28627{{"`Creating URL-Friendly Slugs with JavaScript`"}} end

Function to Convert String to URL Slug

To convert a string to a slug that can be used in a URL, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the String.prototype.toLowerCase() and String.prototype.trim() methods to normalize the string.
  3. Use the String.prototype.replace() method to replace spaces, dashes, and underscores with -, and remove special characters.
  4. Implement the following code:
const slugify = (str) =>
  str
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, "")
    .replace(/[\s_-]+/g, "-")
    .replace(/^-+|-+$/g, "");
  1. 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.

Other JavaScript Tutorials you may like