Regex for URL Slug
This regex matches URL slugs — the URL-friendly version of a title or name. Slugs contain only lowercase letters, numbers, and hyphens, with no consecutive hyphens or leading/trailing hyphens. They are used in blog post URLs, product pages, and any resource where a readable, SEO-friendly URL is needed.
^[a-z0-9]+(?:-[a-z0-9]+)*$ What is the regex pattern for URL Slug?
The regex pattern for URL Slug is ^[a-z0-9]+(?:-[a-z0-9]+)*$. This regex matches URL slugs — the URL-friendly version of a title or name. Slugs contain only lowercase letters, numbers, and hyphens, with no consecutive hyphens or leading/trailing hyphens. They are used in blog post URLs, product pages, and any resource where a readable, SEO-friendly URL is needed. This pattern is commonly used for blog post urls and product page urls.
Test Examples
my-first-blog-post my-first-blog-post product-42 product-42 Invalid Slug! Common Uses
- ✓ Blog post URLs
- ✓ Product page URLs
- ✓ Category permalinks
- ✓ SEO-friendly routing
Variations
Allow underscores
^[a-z0-9]+(?:[-_][a-z0-9]+)*$ Permits underscores as separators too
Allow uppercase
^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$ Case-insensitive slugs
With length limit
^[a-z0-9]+(?:-[a-z0-9]+)*$(?<=.{1,100}) Limits slug to 100 characters
Frequently Asked Questions
How do I generate a slug from a title?
Convert to lowercase, replace spaces with hyphens, remove special characters, collapse consecutive hyphens, and trim hyphens from start and end. Most web frameworks include a built-in slugify function.
Why use hyphens instead of underscores in URLs?
Google treats hyphens as word separators but underscores as word joiners. The URL 'web-development' is seen as two words, while 'web_development' is one. Hyphens are better for SEO.
What is the maximum URL slug length?
There is no strict limit, but keeping slugs under 50-60 characters is recommended for readability and SEO. Longer slugs may be truncated in search results.