27

truncate-middle.js

A JavaScript snippet to truncate the middle of long strings, preserving the start and end. Ideal for displaying filenames, wallet addresses, or IDs in limited space.

javascript utility

When it comes to displaying long strings in the UI, most developers are familiar with the simple CSS styling that limits the text to a specific width, such as 250px. But, what if you need to truncate the middle portion of a long string, allowing you to display both the beginning and end sections? Here is a JavaScript function that efficiently handles this task!

TruncateString Function

To truncate the middle portion of a string, we can employ the following JavaScript function:

function truncateMiddle(str, start = 5, end = 5, dots = '...') {
  if (str.length <= start + end) return str;
  return str.slice(0, start) + dots + str.slice(-end);
}

Step by step

The function takes four parameters:

  • str: The input string to truncate
  • start: Number of characters to keep from the beginning (defaults to 5)
  • end: Number of characters to keep from the end (defaults to 5)
  • dots: The separator string to use between start and end portions (defaults to '...')

Examples

// Example 1: Truncate a long filename
const filename = "very-long-filename-that-needs-truncation.txt";
console.log(truncateMiddle(filename, 10, 4));
// Output: "very-long-...txt"
 
// Example 2: Truncate a wallet address
const walletAddress = "0x1234567890abcdef1234567890abcdef12345678";
console.log(truncateMiddle(walletAddress, 6, 4));
// Output: "0x1234...5678"
 
// Example 3: Truncate with custom separator
const longString = "This is a very long string that needs truncation";
console.log(truncateMiddle(longString, 15, 10, "---"));
// Output: "This is a very---truncation"

Use cases

This approach is particularly useful for:

  • Displaying long filenames in file browsers
  • Showing wallet addresses or transaction IDs in limited space
  • Presenting long URLs or paths in user interfaces
  • Maintaining readability while saving space

The function is lightweight, efficient, and provides a clean solution for truncating strings while preserving the most important parts - the beginning and end.