isValidSlug
Validates whether a string is a valid slug.
1/**
2 * Validates whether a string is a valid slug.
3 *
4 * Rules:
5 * - Lowercase letters (a–z), numbers (0–9), and hyphens (-)
6 * - No leading/trailing hyphens
7 * - No consecutive hyphens
8 *
9 * @param str - The string to validate.
10 * @returns True if valid, false otherwise.
11 */
12export function isValidSlug(str: string): boolean {
13 return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(str);
14}
Strict Slug Compliance
Enforces common slug formatting rules - lowercase alphanumeric characters and single hyphens without leading/trailing or repeated hyphens.
Regex-Based Simplicity
Uses a compact regular expression that is efficient and easy to maintain or adapt.
SEO and URL Safety
Guarantees that generated or validated strings are safe to use in URLs and conform to SEO-friendly standards.
No External Dependencies
Lightweight validation without reliance on third-party libraries or complex logic.
Tests | Examples
1test('valid slugs', () => {
2 expect(isValidSlug('hello-world')).toBe(true);
3 expect(isValidSlug('a1-b2-c3')).toBe(true);
4 expect(isValidSlug('slug')).toBe(true);
5 expect(isValidSlug('x')).toBe(true);
6});
7
8test('invalid slugs - uppercase or symbols', () => {
9 expect(isValidSlug('Hello-World')).toBe(false);
10 expect(isValidSlug('hello_world')).toBe(false);
11 expect(isValidSlug('hello.world')).toBe(false);
12 expect(isValidSlug('hello world')).toBe(false);
13 expect(isValidSlug('hello--world')).toBe(false);
14});
15
16test('invalid slugs - leading/trailing hyphens', () => {
17 expect(isValidSlug('-slug')).toBe(false);
18 expect(isValidSlug('slug-')).toBe(false);
19});
Common Use Cases
URL Generation
Validate slugs used for clean, human-readable URLs in blogs, products, or pages.
CMS Input Validation
Ensure slugs entered by users or generated from titles are safe and properly formatted.
Routing Systems
Confirm that path parameters used in route definitions follow expected slug conventions.
Database Constraints
Prevent invalid slugs from being stored in identifiers or lookup keys tied to URL structures.