stringToSlug
Converts a string into a URL-friendly slug. Transforms the string to lowercase, trims it, replaces non-alphanumeric characters with hyphens, and removes leading/trailing hyphens.
1/**
2 * Converts a string into a URL-friendly slug.
3 * Transforms the string to lowercase, trims it, replaces non-alphanumeric characters
4 * with hyphens, and removes leading/trailing hyphens.
5 *
6 * @param str - The input string to convert.
7 * @returns A slugified version of the string.
8 */
9export function stringToSlug(str: string): string {
10 return str
11 .toLowerCase()
12 .trim()
13 .replace(/[^a-z0-9]+/g, '-')
14 .replace(/^-+|-+$/g, '');
15}
SEO-Friendly Output
Converts strings into clean, lowercase, hyphen-separated slugs ideal for use in URLs and permalinks.
Lightweight and Fast
Uses simple regex-based transformations — no dependencies or complex logic required.
Sanitization Built-In
Filters out unsafe characters and ensures slugs are composed only of alphanumeric segments and hyphens.
Trimming and Normalization
Handles extra spaces and leading/trailing special characters, producing compact and predictable output.
Tests | Examples
1test('stringToSlug - basic conversion', () => {
2 expect(stringToSlug('Hello World')).toBe('hello-world');
3});
4
5test('stringToSlug - trims and lowercases', () => {
6 expect(stringToSlug(' Trim Me ')).toBe('trim-me');
7});
8
9test('stringToSlug - removes special characters', () => {
10 expect(stringToSlug('Café & Restaurant!')).toBe('caf-restaurant');
11});
12
13test('stringToSlug - handles multiple separators', () => {
14 expect(stringToSlug('a___b---c')).toBe('a-b-c');
15});
16
17test('stringToSlug - handles non-latin characters', () => {
18 expect(stringToSlug('こんにちは')).toBe(''); // only a-z0-9 are retained
19});
20
21test('stringToSlug - empty string', () => {
22 expect(stringToSlug('')).toBe('');
23});
Common Use Cases
Generating URL Slugs for Blog Posts or Articles
Turn titles like
"10 Best Practices for Devs!"
into"10-best-practices-for-devs"
.Creating Identifiers for Routing or Search
Use slugified strings as unique, human-readable IDs in React Router, Next.js, or Express apps.
Improving SEO and Readability
Replace spaces and symbols with hyphens to create links that are optimized for search engines.
Generating Safe File Names or Keys
Useful when creating filenames or storage keys based on user input.