| 1 |
/** |
| 2 |
* Slug Generation Utility |
| 3 |
* Generates URL-friendly slugs from text (matches WordPress sanitize_title logic) |
| 4 |
*/ |
| 5 |
|
| 6 |
/** |
| 7 |
* Generate a slug from a string |
| 8 |
* Mimics WordPress sanitize_title() function |
| 9 |
* |
| 10 |
* @param text - The text to convert to a slug |
| 11 |
* @returns A URL-friendly slug |
| 12 |
*/ |
| 13 |
export const generateSlug = (text: string): string => { |
| 14 |
if (!text) return ""; |
| 15 |
|
| 16 |
return ( |
| 17 |
text |
| 18 |
.toLowerCase() |
| 19 |
.trim() |
| 20 |
// Replace spaces and underscores with hyphens |
| 21 |
.replace(/[\s_]+/g, "-") |
| 22 |
// Remove all non-word characters except hyphens. The Unicode property |
| 23 |
// escapes (\p{L} = any letter, \p{N} = any digit) with the `u` flag let |
| 24 |
// non-Latin alphabets through — Cyrillic ("Путешествие"), CJK, Devanagari, |
| 25 |
// Arabic, etc. The previous `\w` shortcut was ASCII-only and stripped |
| 26 |
// every Russian letter, producing an empty slug. WordPress's own |
| 27 |
// sanitize_title() preserves these scripts server-side, so this matches. |
| 28 |
.replace(/[^\p{L}\p{N}-]+/gu, "") |
| 29 |
// Replace multiple consecutive hyphens with a single hyphen |
| 30 |
.replace(/-+/g, "-") |
| 31 |
// Remove leading and trailing hyphens |
| 32 |
.replace(/^-+|-+$/g, "") |
| 33 |
); |
| 34 |
}; |
| 35 |
|
| 36 |
/** |
| 37 |
* Generate a unique slug by appending a number if needed |
| 38 |
* |
| 39 |
* @param baseSlug - The base slug |
| 40 |
* @param existingSlugs - Array of existing slugs to check against |
| 41 |
* @returns A unique slug |
| 42 |
*/ |
| 43 |
export const generateUniqueSlug = ( |
| 44 |
baseSlug: string, |
| 45 |
existingSlugs: string[], |
| 46 |
): string => { |
| 47 |
let slug = generateSlug(baseSlug); |
| 48 |
|
| 49 |
if (!slug) { |
| 50 |
slug = "untitled"; |
| 51 |
} |
| 52 |
|
| 53 |
// If slug is already unique, return it |
| 54 |
if (!existingSlugs.includes(slug)) { |
| 55 |
return slug; |
| 56 |
} |
| 57 |
|
| 58 |
// Try appending numbers until we find a unique slug |
| 59 |
let counter = 1; |
| 60 |
let uniqueSlug = `${slug}-${counter}`; |
| 61 |
|
| 62 |
while (existingSlugs.includes(uniqueSlug)) { |
| 63 |
counter++; |
| 64 |
uniqueSlug = `${slug}-${counter}`; |
| 65 |
} |
| 66 |
|
| 67 |
return uniqueSlug; |
| 68 |
}; |
| 69 |
|