DEV Community

fikriqx
fikriqx

Posted on

Convert String Title to Slug in Javascript

To convert a title to a slug format using JavaScript, you need to transform the title into a URL-friendly string. This typically involves lowercasing the string, replacing spaces and other non-alphanumeric characters with hyphens, and removing any leading or trailing hyphens. Here is a step-by-step guide on how to achieve this:

Convert the string to lowercase: This ensures consistency in the slug format.

  1. Replace spaces and non-alphanumeric characters with hyphens: 2. This makes the string URL-friendly.
  2. Remove leading and trailing hyphens: Clean up any extra hyphens added at the start or end of the string.

Here's a sample JavaScript function to do this:

function stringToSlug(title) {
  return title
    .toLowerCase()                           // Convert to lowercase
    .replace(/[^a-z0-9 -]/g, '')             // Remove invalid characters
    .replace(/\s+/g, '-')                    // Replace spaces with hyphens
    .replace(/-+/g, '-')                     // Replace multiple hyphens with a single hyphen
    .replace(/^-+|-+$/g, '');                // Remove leading and trailing hyphens
}

// Example usage:
const title = "This is a Sample Title!";
const slug = stringToSlug(title);
console.log(slug);  // Output: "this-is-a-sample-title"
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. toLowerCase(): Converts the entire string to lowercase.
  2. replace(/[^a-z0-9 -]/g, ''): Removes any characters that are not lowercase letters, numbers, spaces, or hyphens.
  3. replace(/\s+/g, '-'): Replaces one or more spaces with a 4. single hyphen.
  4. replace(/-+/g, '-'): Replaces multiple consecutive hyphens with a single hyphen.
  5. replace(/^-+|-+$/g, ''): Removes leading and trailing hyphens.

This function will help you convert any title string into a clean, URL-friendly slug.

Top comments (0)