blog.hangerthem.com/utils/slug.ts

27 lines
730 B
TypeScript

/**
* Converts a string into a URL-friendly slug.
* @param text - The input string to be converted into a slug.
* @returns A URL-friendly slug string.
*/
export function slugify(text: string): string {
return text
.toLowerCase()
.trim()
.replace(/\s+/g, '-')
.replace(/[^\w-]/g, '')
}
/**
* Finds a slug in an array of strings, ignoring case.
* @param slug - The slug to search for.
* @param array - The array of strings to search within.
* @returns The matching string from the array if found, otherwise null.
*/
export function findSlugInArray(slug: string, array: string[]): string | null {
for (const item of array) {
if (slug === slugify(item)) {
return item
}
}
return null
}