How to convert a text into slug using Javascript

Aug 10, 2024, 09:10 PM

While writing blog posts, you often need to add slug, here is how to write a function that converts any texts into a slug.


Let's write a function in Javascript that sluggify any text. This function might help you in creating your blog in markdown like the way I used it in my blog.

function slugify(text) {
  return text
    .toString()                  // Convert to string
    .toLowerCase()               // Convert to lowercase
    .trim()                      // Remove whitespace from both sides
    .replace(/\s+/g, '-')        // Replace spaces with -
    .replace(/[^\w\-]+/g, '')    // Remove all non-word chars
    .replace(/\-\-+/g, '-');     // Replace multiple - with single -
}

// Example usage
const title = "Hello World! This is a Test.";
const slug = slugify(title);
console.log(slug);  // Output: "hello-world-this-is-a-test"