# Truncate a string at full words

Cut at the last space that fits, then add a suffix.

Canonical: https://1loc.dev/string/truncate-a-string-at-full-words/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Local fixtures; no external services
Updated: 2026-10-28

## Implementation

```javascript
function truncateWords({ text, max, suffix }) { if (text.length <= max) return text; const cut = text.slice(0, max - suffix.length); const space = cut.lastIndexOf(' '); return `${space > 0 ? cut.slice(0, space) : cut}${suffix}`; }
```

## Input

```json
{
  "text": "Your order 8812 is out for delivery",
  "max": 20,
  "suffix": "…"
}
```

## Expected output

```json
"Your order 8812 is…"
```

## Edge case

Input:
```json
{
  "text": "Supercalifragilistic",
  "max": 10,
  "suffix": "…"
}
```
Output:
```json
"Supercali…"
```

## Limits

- The original truncated strings exactly max long and returned only the suffix when the first word was too long; both are fixed.
- Handy for preview text and notification titles; length is in UTF-16 code units.

The lab validates types and size before calling this function. Add equivalent validation at your own trust boundary.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/truncate-a-string-at-full-words.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Keeps strings exactly max long and falls back to a hard cut when the first word is too long; the original returned only the suffix. Original MDX retained as inert source evidence.
