30 lines
750 B
TypeScript
30 lines
750 B
TypeScript
export function slugify(text: string): string {
|
|
return text
|
|
.toString()
|
|
.toLowerCase()
|
|
.trim()
|
|
.replace(/\s+/g, '-')
|
|
.replace(/[^\w\-]+/g, '')
|
|
.replace(/\-\-+/g, '-')
|
|
.replace(/^-+/, '')
|
|
.replace(/-+$/, '')
|
|
}
|
|
|
|
export async function generateUniqueSlug(
|
|
baseSlug: string,
|
|
checkUnique: (slug: string) => Promise<boolean>,
|
|
maxAttempts = 10
|
|
): Promise<string> {
|
|
let slug = baseSlug
|
|
let attempt = 1
|
|
|
|
while (await checkUnique(slug)) {
|
|
if (attempt >= maxAttempts) {
|
|
throw new Error(`Could not generate unique slug after ${maxAttempts} attempts`)
|
|
}
|
|
slug = `${baseSlug}-${attempt}`
|
|
attempt++
|
|
}
|
|
|
|
return slug
|
|
} |