|
1
|
/** |
|
2
|
* Helper method to create a URL-friendly "handle" from a string value. |
|
3
|
* |
|
4
|
* - Converts the value to lowercase |
|
5
|
* - Preserves letters from any language (Persian, Arabic, Japanese, Chinese, Korean, Russian, etc.) |
|
6
|
* - Removes special characters (apostrophes, punctuation, symbols, etc.) |
|
7
|
* - Replaces spaces and underscores with hyphens |
|
8
|
* - Collapses multiple hyphens into a single hyphen |
|
9
|
* - Falls back to a random suffix if the result is empty |
|
10
|
* |
|
11
|
*/ |
|
12
|
export const toHandle = (value: string): string => { |
|
13
|
let handle = value |
|
14
|
.toLowerCase() |
|
15
|
.replace(/ß/g, "ss") |
|
16
|
.replace(/[^\p{L}\p{N}\s_-]/gu, "") |
|
17
|
.replace(/[\s_]+/g, "-") |
|
18
|
.replace(/-+/g, "-") |
|
19
|
.replace(/^-|-$/g, "") |
|
20
|
|
|
21
|
if (!handle) { |
|
22
|
handle = `product-${Math.random().toString(36).substring(2, 8)}` |
|
23
|
} |
|
24
|
|
|
25
|
return handle |
|
26
|
} |