datasquirel/package-shared/utils/slugify.ts

27 lines
663 B
TypeScript
Raw Normal View History

2024-12-12 05:43:07 +00:00
// @ts-check
/**
* # Return the slug of a string
2025-01-10 19:10:28 +00:00
*
2024-12-12 05:43:07 +00:00
* @example
* slugify("Hello World") // "hello-world"
* slugify("Yes!") // "yes"
* slugify("Hello!!! World!") // "hello-world"
*/
2025-01-10 19:10:28 +00:00
export default function slugify(str: string): string {
2024-12-12 05:43:07 +00:00
try {
return String(str)
.trim()
.toLowerCase()
.replace(/ {2,}/g, " ")
.replace(/ /g, "-")
2024-12-12 06:19:48 +00:00
.replace(/[^a-z0-9]/g, "-")
.replace(/-{2,}/g, "-")
2024-12-12 05:43:07 +00:00
.replace(/^-/, "")
.replace(/-$/, "");
2025-01-10 19:10:28 +00:00
} catch (/** @type {any} */ error: any) {
2024-12-12 05:43:07 +00:00
console.log(`Slugify ERROR: ${error.message}`);
return "";
}
2025-01-10 19:10:28 +00:00
}