Skip to content

Commit 16f35ce

Browse files
authored
fix(shared): truncate keeps emoji whole (pingdotgg#27841)
1 parent dcc31b8 commit 16f35ce

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { truncate } from "./String.ts";
4+
5+
describe("truncate", () => {
6+
it("leaves short text alone", () => {
7+
expect(truncate("hello", 50)).toBe("hello");
8+
});
9+
10+
it("cuts by Unicode code point so emoji stay whole", () => {
11+
expect(truncate("πŸ‘πŸ‘πŸ‘", 5)).toBe("πŸ‘πŸ‘πŸ‘");
12+
expect(truncate("πŸ‘πŸ‘πŸ‘πŸ‘", 3)).toBe("πŸ‘πŸ‘πŸ‘...");
13+
});
14+
15+
it("trims before measuring", () => {
16+
expect(truncate(" hello ", 5)).toBe("hello");
17+
});
18+
});
Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
export function truncate(text: string, maxLength = 50): string {
22
const trimmed = text.trim();
3-
if (trimmed.length <= maxLength) {
3+
const characters = Array.from(trimmed);
4+
if (characters.length <= maxLength) {
45
return trimmed;
56
}
67

7-
return `${trimmed.slice(0, maxLength)}...`;
8+
return `${characters.slice(0, maxLength).join("")}...`;
89
}

0 commit comments

Comments
Β (0)