diff --git a/src/lib/slugify.ts b/src/lib/slugify.ts new file mode 100644 index 0000000..8f3d2c4 --- /dev/null +++ b/src/lib/slugify.ts @@ -0,0 +1,8 @@ +export function slugify(text: string): string { + return text + .toLowerCase() + .replace(/[^a-z0-9\s-]/g, '') + .replace(/[\s]+/g, '-') + .replace(/-+/g, '-') + .replace(/^-|-$/g, ''); +} diff --git a/tests/unit/slugify.test.ts b/tests/unit/slugify.test.ts new file mode 100644 index 0000000..f80a027 --- /dev/null +++ b/tests/unit/slugify.test.ts @@ -0,0 +1,20 @@ +import { describe, it, expect } from 'vitest'; +import { slugify } from '$lib/slugify'; + +describe('slugify', () => { + it('converts to lowercase with hyphens', () => { + expect(slugify('Hello World')).toBe('hello-world'); + }); + + it('removes special characters', () => { + expect(slugify("Buddy's Adventure!")).toBe('buddys-adventure'); + }); + + it('collapses multiple hyphens', () => { + expect(slugify('foo bar---baz')).toBe('foo-bar-baz'); + }); + + it('trims leading and trailing hyphens', () => { + expect(slugify(' hello ')).toBe('hello'); + }); +});