Skip to content
Johnu Marattil

← Lab

Truncating the middle of a string

Johnu Marattilui engineering1 min

CSS can stop a long string at a fixed width, but it always cuts the end. For a filename, a wallet address or a transaction ID, the end is often the part people need. This function keeps the start and the end and cuts the middle.

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

It takes four parameters:

  • str: the string to shorten
  • start: how many characters to keep from the beginning (default 5)
  • end: how many characters to keep from the end (default 5)
  • dots: what goes between the two halves (default '...')

Examples

// A long filename
truncateMiddle('very-long-filename-that-needs-truncation.txt', 10, 4);
// "very-long-...txt"

// A wallet address
truncateMiddle('0x1234567890abcdef1234567890abcdef12345678', 6, 4);
// "0x1234...5678"

// A custom separator
truncateMiddle('This is a very long string that needs truncation', 15, 10, '---');
// "This is a very---truncation"

Where I use it

  • Long filenames in file browsers
  • Wallet addresses and transaction IDs in tight columns
  • URLs and paths that have to fit on one line

If the string is already short enough, it comes back unchanged.

Filed under ui engineering