PYTHON
Sanitize String for URL Slug Generation
A Python snippet for converting a string into a clean, URL-friendly slug by replacing special characters and spaces with hyphens.
import re
def generate_slug(text):
# Convert to lowercase
text = text.lower()
# Replace non-alphanumeric characters (except hyphens and spaces) with a space
text = re.sub(r'[^a-z0-9\s-]', '', text)
# Replace spaces with a single hyphen
text = re.sub(r'\s+', '-', text)
# Trim leading/trailing hyphens
text = text.strip('-')
return text
# Example Usage:
print(generate_slug("My Awesome Article Title!")) # my-awesome-article-title
print(generate_slug("Another Title with Special Chars & numbers 123")) # another-title-with-special-chars-numbers-123
print(generate_slug(" Leading/Trailing Spaces ")) # leading-trailing-spaces
How it works: The Python `generate_slug` function converts an input string into a URL-friendly slug. It first converts the text to lowercase, then uses regex to remove unwanted characters and replace spaces with single hyphens. Finally, it trims any leading or trailing hyphens, resulting in a clean, web-compatible string.