Files
30-seconds-of-code/snippets/slugify.md
2020-10-04 08:45:43 +02:00

578 B

title, tags
title tags
slugify function,intermediate

Convert a string to a URL-friendly slug.

  • Make the string lowercase and remove leading or trailing whitespace.
  • Remove all characters that are not words, whitespace or hyphens.
  • Replace whitespace with a single hyphen (-).
  • Remove any leading or trailing hyphens.
const slugify = (string) => {
  const slug = string
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_-]+/g, '-')
    .replace(/^-+|-+$/g, '');
  return slug;
};
slugify('Hello World!'); // 'hello-world'