UNPKG

@mintlify/common

Version:

Commonly shared code within Mintlify

17 lines (16 loc) 710 B
/** * Truncates a string at word boundaries to ensure it doesn't exceed the specified length * @param text - The text to truncate * @param maxLength - Maximum allowed length * @returns Truncated text that ends on a complete word, or character-truncated fallback if no word fits */ export function truncateAtWordBoundary(text, maxLength) { const normalizedText = text.replace(/\s+/g, ' ').trim(); if (normalizedText.length <= maxLength) return normalizedText; const slice = normalizedText.slice(0, maxLength + 1); const lastSpace = slice.lastIndexOf(' '); return lastSpace === -1 ? normalizedText.slice(0, maxLength).trim() : slice.slice(0, lastSpace).trim(); }