URL Slug in JS
Validate URL slugs: lowercase letters and digits separated by single hyphens, no leading/trailing hyphens.
Try it in the JS tester →Pattern
regexJS
^[a-z0-9]+(?:-[a-z0-9]+)*$JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("^[a-z0-9]+(?:-[a-z0-9]+)*$", "");
const input = "my-blog-post";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
Anchored with ^ and $. Requires at least one alphanumeric character. Hyphens can only appear between alphanumeric groups — not at start or end.
Examples
Input
my-blog-postMatches
my-blog-post
Input
hello-world-123Matches
hello-world-123
Input
-bad-slug-No match
—