ReactUseKit

truncateText

Truncate text to a maximum length with ellipsis.

Installation

pnpm dlx shadcn@latest add @reactusekit/truncate-text

Usage

import { truncateText } from "@/lib/truncate-text"

function App() {
  const longText = "This is a very long text that needs to be truncated"
  const shortText = truncateText(longText, 20)

  return (
    <div>
      <p>Original: {longText}</p>
      <p>Truncated: {shortText}</p>
    </div>
  )
}

API

Parameters

ParameterTypeDescription
textstringThe text to truncate
maxLengthnumberMaximum length before truncation

Returns

TypeDescription
stringThe truncated text with ellipsis if needed