Text Shortener
In some scenarios, CSS text-overflow: ellipses does not work. In those cases this comes handy.
shorten-text.ts
/**
* @description Shortens a string to a specified length and adds ellipses.
* @param text The string to shorten.
* @param length The maximum length of the string.
* @param splitAt The position to split the string. Can be "middle" or "end".
* @returns The shortened string.
*/
export function shortenText(
text: string,
length: number,
splitAt: "middle" | "end" = "end"
): string {
if (text.length <= length) {
return text;
} else {
const ellipsesLength = 3;
const halfEllipsesLength = Math.floor(ellipsesLength / 2);
const leftHalf = text.slice(0, length / 2 - halfEllipsesLength);
const rightHalf = text.slice(text.length - length / 2 + halfEllipsesLength);
return splitAt === "middle"
? `${leftHalf}...${rightHalf}`
: text.slice(0, length - ellipsesLength) + "...";
}
}
Usage
<p className="text-muted-foreground">
{shortenText("a very long text", 10, "middle")}
</p>
Converts a very long text to a ver... text.