Shorten text to a maximum length with ellipsis

Shorten a JavaScript string at its start, middle, or end while reserving room for a suffix.

freeworks offlinenothing uploaded
ToolText Truncator
Input
Output
Put this on your own site

The frame below runs the same code as this page, in the reader's own browser. Nothing is sent to us, and nothing is sent to you.

Pick a dark background and the text and panels follow it, so the frame stays readable on a dark page.

Preview

How it works

The suffix length is subtracted from the maximum before UTF-16 slicing keeps a prefix, suffix, or two equal halves. Word preservation may retreat to a nearby ordinary space; when the suffix consumes the allowance, only a sliced suffix remains.

  • The initial 100-unit ceiling, three periods, end position, and word preservation fit a general preview.
  • The limit counts UTF-16 units rather than bytes, code points, grapheme clusters, or rendered width.

Worked example

Truncate a long sentence
Shorten text to a maximum length with ellipsis
Input
											Input: The quick brown fox jumps over the lazy dog in the garden
Max length: 30
										
Output
												The quick brown fox jumps...
											

When to use this

Search cards shorten descriptions, log viewers retain long-line tails, and filename previews preserve both a beginning and extension.

Edge cases

  • An emoji or combining sequence can be cut between UTF-16 or grapheme components.
  • An odd middle allowance uses two floor-sized halves and can finish one unit below the maximum.
  • A suffix longer than the maximum is itself sliced and leaves no source characters.

References