avatar

Le Do Nghiem

Software Engineer

  • About me
  • Books
  • Snippets
  • Blog

© 2026 Le Do Nghiem. All rights reserved.

Contact |

Back to Snippets

truncateString Function

Truncate long strings with ellipsis, useful for previews and card layouts.

LanguageTypeScript
Last UpdatedApr 29, 2025
truncate-string.ts
export function truncateString(
  str: string,
  maxLength: number,
  suffix: string = '...'
): string {
  if (str.length <= maxLength) {
    return str;
  }
  return str.slice(0, maxLength - suffix.length) + suffix;
}

When displaying text in cards, previews, or limited space, you often need to truncate long strings. This utility makes it easy to cut text at a specific length with an ellipsis.

export function truncateString(
  str: string,
  maxLength: number,
  suffix: string = '...'
): string {
  if (str.length <= maxLength) {
    return str;
  }
  return str.slice(0, maxLength - suffix.length) + suffix;
}

How It Works

  • Checks if the string exceeds the maximum length.
  • If not, returns the original string.
  • Otherwise, slices the string and appends the suffix (default: '...').

Example Usage

truncateString("This is a very long string", 20);
// => "This is a very lon..."

truncateString("Short", 20);
// => "Short"

truncateString("Hello world", 8, "...");
// => "Hello..."

Advanced Version with Word Boundary

export function truncateStringAtWord(
  str: string,
  maxLength: number,
  suffix: string = '...'
): string {
  if (str.length <= maxLength) {
    return str;
  }

  const truncated = str.slice(0, maxLength);
  const lastSpace = truncated.lastIndexOf(' ');

  if (lastSpace > 0) {
    return truncated.slice(0, lastSpace) + suffix;
  }

  return truncated + suffix;
}

This version respects word boundaries, avoiding cuts in the middle of words:

truncateStringAtWord("This is a very long string", 20);
// => "This is a very..."

Use Cases

  • Blog post excerpts
  • Product descriptions in cards
  • User bio previews
  • Comment previews
  • Search result snippets

Notes

  • Simple version may cut words in half.
  • Use the word-boundary version for better readability.
  • Consider CSS text-overflow: ellipsis for single-line truncation.
  • The suffix length is automatically accounted for in the truncation.

A simple utility that helps keep your UI clean and prevents text overflow in constrained layouts.

Previous Snippet

useClickOutside Hook

Next Snippet

useFetch Hook