String Utilities
truncateString
Truncates a string to a given length and appends an ellipsis if necessary
Usage
import { truncateString } from '@/lib/truncate-string';
const result = truncateString("Hello TypeScript World", 10);
console.log(result); // "Hello Type..."Installation
pnpm dlx shadcn@latest add https://utilcn.dev/r/truncate-string.jsonbunx --bun shadcn@latest add https://utilcn.dev/r/truncate-string.jsonnpx shadcn@latest add https://utilcn.dev/r/truncate-string.jsonyarn shadcn@latest add https://utilcn.dev/r/truncate-string.jsonParameters
| Parameter | Type | Description |
|---|---|---|
str | string | The input string |
length | number | The maximum length of the string |
Returns
string - The truncated string with "..." if it exceeded the limit.
Examples
truncateString("Hello TypeScript World", 10); // "Hello Type..."
truncateString("Short", 10); // "Short"
truncateString("Exactly ten", 10); // "Exactly ten"
truncateString("This is a very long sentence", 15); // "This is a very ..."
truncateString("", 5); // ""Implementation
export function truncateString(str: string, length: number): string {
return str.length > length ? `${str.slice(0, length)}...` : str;
}Note
The ellipsis ("...") is added to the truncated string, so the total length will be length + 3 characters when truncation occurs.