Files
30-seconds-of-code/snippets/slugify.md
Jay Patel 336b5b78a8 Added slugify (#286)
Co-authored-by: Isabelle Viktoria Maciohsek <maciv@hotmail.gr>
2020-10-05 21:57:34 +03:00

516 B

title, tags
title tags
slugify string,regex,intermediate

Converts a string to a URL-friendly slug.

  • Use str.lower() and str.strip() to normalize the input string.
  • Use re.sub() to to replace spaces, dashes and underscores with - and remove special characters.
import re

def slugify(s):
  s = s.lower().strip()
  s = re.sub(r'[^\w\s-]', '', s)
  s = re.sub(r'[\s_-]+', '-', s)
  s = re.sub(r'^-+|-+$', '', s)
  return s
slugify('Hello World!') # 'hello-world'