Regex for a URL slug
A regular expression that checks a URL slug such as regex-examples, and the few lines of code that turn any title, accents and all, into one.
This tool runs in your browser. We never send what you type or paste to a server.
The pattern
/^[a-z0-9]+(?:-[a-z0-9]+)*$/A slug is the readable part of a URL, such as regex-examples in /regex-examples/. Restricting it to lowercase ASCII letters, digits and single hyphens keeps URLs readable, avoids percent-encoding and means there is only one way to write each address, which matters because most web servers treat paths as case-sensitive.
The tester at the top of this page is loaded with this pattern and the examples below, one per line. It adds the m flag so that ^ and $ apply to each line, and g to show every match. Edit either box to try your own input.
How it works, token by token
| Part | Meaning |
|---|---|
^ | Start of the string. |
[a-z0-9]+ | A first word of lowercase letters and digits. |
(?:-[a-z0-9]+)* | Then any number of further words, each after exactly one hyphen. Because every hyphen must be followed by a word, the slug cannot end with a hyphen or contain two in a row. |
$ | End of the string. |
What it matches and what it rejects
| Input | Result | Why |
|---|---|---|
hello-world | matches | Two words. |
regex-examples | matches | Another. |
2026-review | matches | Digits are fine. |
a | matches | One character. |
Hello-World | rejected | Capitals. |
hello--world | rejected | Two hyphens in a row. |
-hello | rejected | A leading hyphen. |
hello- | rejected | A trailing one. |
hello_world | rejected | Underscores (see the variant below). |
hello world | rejected | A space. |
café | rejected | An accented letter. |
(empty string) | rejected | Empty. |
Making a slug from a title
Validation is the easy half. Creating a slug means removing accents, lowercasing, and turning every run of other characters into one hyphen. Unicode normalisation (NFKD) splits a letter like é into e plus a combining accent, which can then be dropped:
function slugify(title) {
return title
.normalize('NFKD') // split é into e and a combining accent
.replace(/[\u0300-\u036f]/g, '') // drop the accents
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
console.log(slugify('10 Tips for Writing Better Café Menus!')); // → 10-tips-for-writing-better-cafe-menus
console.log(slugify(' Ünïcödé & "quotes" ')); // → unicode-quotesimport re
import unicodedata
def slugify(title):
s = unicodedata.normalize('NFKD', title).encode('ascii', 'ignore').decode('ascii')
s = re.sub(r'[^a-z0-9]+', '-', s.lower())
return s.strip('-')
print(slugify('10 Tips for Writing Better Café Menus!')) # → 10-tips-for-writing-better-cafe-menus
print(slugify(' Ünïcödé & "quotes" ')) # → unicode-quotesBoth functions drop characters that have no ASCII form, such as Chinese or Cyrillic text, so a title written entirely in such a script becomes an empty slug. Check for that and fall back to an ID, or keep the original letters: modern browsers display them in the address bar, and the slug generator lets you try both.
Underscores and length
Hyphens are the usual separator, but some systems use underscores. To allow either:
/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/| Input | Result | Why |
|---|---|---|
hello_world | matches | Underscore. |
snake_and-kebab | matches | Either separator. |
hello__world | rejected | Still one separator at a time. |
_hello | rejected | Not at the start. |
A lookahead at the start can cap the total length without changing the rest of the pattern. (?=.{1,60}$) checks that between 1 and 60 characters remain before the end, then the main pattern runs from the start again:
/^(?=.{1,60}$)[a-z0-9]+(?:-[a-z0-9]+)*$/| Input | Result | Why |
|---|---|---|
hello-world | matches | Short enough. |
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | matches | Exactly 60 characters. |
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | rejected | One too many. |
hello--world | rejected | The other rules still apply. |
Before you save a slug
The pattern says a slug is well formed, not that it is free to use. Check that it is unique within its section, and add -2, -3 and so on if it is not. Keep a short list of words your routes already use, such as new, edit or admin, so that a page called "New" cannot hide /posts/new/. And once a page is published, keep its slug: if the title changes later, redirect the old address rather than breaking links.
In JavaScript, Python, PHP and C#
JavaScript
const re = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
console.log(re.test('hello-world')); // → true
console.log(re.test('Hello-World')); // → false
Python
import re
pattern = re.compile(r'[a-z0-9]+(?:-[a-z0-9]+)*')
print(bool(pattern.fullmatch('hello-world'))) # → True
print(bool(pattern.fullmatch('Hello-World'))) # → False
PHP
<?php
$pattern = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/D';
echo preg_match($pattern, 'hello-world'), "\n"; // → 1
echo preg_match($pattern, 'Hello-World'), "\n"; // → 0
C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^[a-z0-9]+(?:-[a-z0-9]+)*\z");
Console.WriteLine(pattern.IsMatch("hello-world")); // → True
Console.WriteLine(pattern.IsMatch("Hello-World")); // → FalseEach version checks the whole string. JavaScript's $ only matches at the very end, but Python, PHP and .NET also let $ match just before a final line break, so "abc\n" could slip through. The Python version uses re.fullmatch (so the ^ and $ are dropped), PHP adds the D modifier, and C# ends with \z.
The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.
Questions
What is the regex for a URL slug?
^[a-z0-9]+(?:-[a-z0-9]+)*$ allows lowercase letters and digits separated by single hyphens, with no hyphen at either end.
Should slugs use hyphens or underscores?
Hyphens are the common convention, and Google's URL structure guidance recommends hyphens over underscores to separate words. Use underscores only if an existing system needs them.
How do I convert a title to a slug?
Normalise to NFKD, remove the combining accents, lowercase, replace every run of characters other than a to z and 0 to 9 with a hyphen, and trim hyphens from the ends. The code on this page does exactly that.