Strings
Utility functions to transform, format, and manipulate text.
Slugify
Transforms a string into a 'slug'. A slug is the kebab-case version of a string, made URL-friendly by stripping out special characters.
export function slugify(text: string) {
return text
.toString()
.toLowerCase()
.trim()
.replace(/\s+/g, "-")
.replace(/&/g, "-and-")
.replace(/[^\w-]+/g, "")
.replace(/--+/g, "-");
}Slug to camelCase
Transforms a 'slug' into a camelCase string.
export function toCamelCase = (slug: string) {
const regex = /^[a-z-]+$/;
if (!regex.test(slug)) {
throw new Error("Invalid slug");
}
return slug
.split("-")
.map((word, index) =>
index ? word.charAt(0).toUpperCase() + word.slice(1) : word
)
.join("");
};Slug to TitleCase
Transforms a 'slug' string into a title case string.
export function slugToTitle(slug: string) {
const exceptions = [
"the",
"and",
"or",
"but",
"nor",
"a",
"an",
"so",
"for",
"yet",
"at",
"by",
"from",
"of",
"on",
"to",
"with",
"in",
"up",
"over",
"as",
];
const words = slug.split("-");
return words
.map((word, index) => {
if (
index === 0 ||
index === words.length - 1 ||
!exceptions.includes(word)
) {
return word.charAt(0).toUpperCase() + word.slice(1);
} else {
return word;
}
})
.join(" ");
};