New blogMaking an AI Agent You Can Trust With Money

★ Web · regex

Regex for URL Slug

The standard SEO-friendly slug: lowercase letters and digits in words separated by single hyphens, with no leading, trailing or doubled hyphens.

  • Runs in your browser
  • No signup

Try the url slug pattern

Read it in plain English (best-effort)

  • ^start of a line
  • [a-z0-9]one character from: a–z, 0–9
  • +one or more of the previous
  • (?:start a group (not captured)
  • -the character '-'
  • [a-z0-9]one character from: a–z, 0–9
  • +one or more of the previous
  • )end of group
  • *zero or more of the previous
  • $end of a line

One sample per line works well with the m flag on anchored patterns.

Waiting for a pattern
01

The pattern, piece by piece

/^[a-z0-9]+(?:-[a-z0-9]+)*$/
Pattern explanation
PartWhat it does
^[a-z0-9]+first word: lowercase letters or digits
(?:-[a-z0-9]+)*more words, each after exactly one hyphen
$end of the string
02

What it accepts and rejects

Every sample below is checked automatically in JavaScript and Python. The tester above is preloaded with all of them, one per line.

Should match
Should match
hello-world✓
a✓
post-123✓
2026-recap✓
seo✓
my-first-post-2✓
Should not match
Should not match
Hello-World✗
hello--world✗
-hello✗
hello-✗
hello_world✗
hello world✗
03

Copy it into your code

RE2-safeNo lookarounds or backreferences, so the same pattern works in Go's RE2 engine and in Rust's regex crate.

const slugRe = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

export function isValidSlug(value) {
  return slugRe.test(value.trim());
}
04

When not to use regex for this

Don't make users type valid slugs. Generate them: lowercase the title, strip accents, replace non-alphanumerics with hyphens and collapse repeats. Use the regex to validate the result.

05

Questions engineers actually ask

Should slugs allow uppercase?
Avoid it. URLs are case-sensitive on most servers, so mixed case creates duplicate pages and broken links.
Are underscores bad for SEO?
Google treats hyphens as word separators and underscores as joiners, so hyphens are the safer convention.
What is catastrophic backtracking?
Some patterns, usually nested quantifiers like (a+)+, make a backtracking engine try an exponential number of paths on input that almost matches. The tester stops any run after 300ms, so a bad pattern can't freeze your tab. In production, that same pattern can take down a server (a ReDoS attack).
06

More web patterns

07

More from the workbench

Fine print

Tools: on the house.
Engineer: by the hour.

The regex was free. Code that doesn't need one is the upgrade: typed schemas, validated once at the edge, trusted everywhere after.

I'm Himanshu, an AI and full-stack engineer. I build MVPs, AI agents and the growth plumbing around them for early-stage startups.