Skip to content

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.

Pattern
^[a-z0-9]+(?:-[a-z0-9]+)*$
Test this pattern in the Regex Tester →

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

Match
my-first-blog-post
Matches: my-first-blog-post
Match
product-42
Matches: product-42
No Match
Invalid Slug!

Common Uses

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.

Related Patterns

Username

^[a-zA-Z0-9_-]{3,20}$

Domain Name

^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-z...

URL

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]...

Related Reading

Regex Cheat Sheet with Examples for Developers → URL Encoding Special Characters →