Text Shortener

In some scenarios, CSS text-overflow: ellipses does not work. In those cases this comes handy.

shorten-text.ts

ts
1/**
2 * @description Shortens a string to a specified length and adds ellipses.
3 * @param text The string to shorten.
4 * @param length The maximum length of the string.
5 * @param splitAt The position to split the string. Can be "middle" or "end".
6 * @returns The shortened string.
7 */
8export function shortenText(
9  text: string,
10  length: number,
11  splitAt: "middle" | "end" = "end"
12): string {
13  if (text.length <= length) {
14    return text;
15  } else {
16    const ellipsesLength = 3;
17    const halfEllipsesLength = Math.floor(ellipsesLength / 2);
18    const leftHalf = text.slice(0, length / 2 - halfEllipsesLength);
19    const rightHalf = text.slice(text.length - length / 2 + halfEllipsesLength);
20    return splitAt === "middle"
21      ? `${leftHalf}...${rightHalf}`
22      : text.slice(0, length - ellipsesLength) + "...";
23  }
24}

Usage

tsx
1<p className="text-muted-foreground">
2  {shortenText("a very long text", 10, "middle")}
3</p>

Converts a very long text to a ver... text.


Loved this post?

Comments

Interested in
working
with me?

Let's Connect

Stay in touch 👇

© 2021 - 2025 itsrakesh. v2.