datasquirel/package-shared/utils/slugify.ts
2025-01-10 20:10:28 +01:00

27 lines
663 B
TypeScript

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