🔍Regex Recipes

URL Slug Validation

Validate URL-friendly slugs with lowercase letters, numbers, and hyphens.

Pattern

^[a-z0-9]+(?:-[a-z0-9]+)*$

Explanation

Matches lowercase alphanumeric strings with hyphens as separators. No leading, trailing, or consecutive hyphens.

Examples

Valid slug
Input
hello-world
Output
✓ Match
Valid with numbers
Input
post-123-update
Output
✓ Match
Invalid - uppercase
Input
Hello-World
Output
✗ No match
Invalid - trailing hyphen
Input
hello-world-
Output
✗ No match
Invalid - spaces
Input
hello world
Output
✗ No match

Code Examples

JavaScript - Generate Slug
function createSlug(text) {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '');
}

const slug = createSlug('Hello World!'); // 'hello-world'

Try it Now

💡 Tips

  • Always normalize to lowercase before validation
  • Remove diacritics for international characters
  • Consider maximum length limits (typically 50-100 chars)
  • Preserve SEO-friendly keywords in slugs