export function unslugify(slug: string, {
separator = "-",
replaceWith = " ",
format = "none",
} = {}): string | undefined {
// Throw an error if the slug parameter is not a valid non-null string
if (!slug || typeof slug !== "string") {
throw new Error("Slug must be a non-null string");
}
// First remove extra separator
slug = slug.replace(new RegExp(`[${separator}]+`, "g"), separator);
// Split the slug on the separator,
// replace the separator with the desired string then trim unecessary whitespace
const unslugified = slug.split(separator).join(replaceWith).trim();
switch (format) {
case "none":
return unslugified;
case "lowercase":
return unslugified.toLowerCase();
case "uppercase":
return unslugified.toUpperCase();
case "capitalize":
return unslugified.replace(/\w\S*/g, (txt) => {
return txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase();
});
case "capitalize-first":
return unslugified.charAt(0).toUpperCase() + unslugified.substring(1).toLowerCase();
default:
return unslugified
}
}