Skip to content
JavaScript

String Truncation

Truncate a string and append an ellipsis.

By EZ4Code Team
stringtruncate

Code

function truncate(str, len = 20, suffix = "...") {
  if (str.length <= len) return str;
  return str.slice(0, len) + suffix;
}

// Truncate by bytes (Chinese chars take 2 bytes)
function truncateByBytes(str, bytes) {
  let count = 0, i = 0;
  for (; i < str.length; i++) {
    count += str.charCodeAt(i) > 255 ? 2 : 1;
    if (count > bytes) break;
  }
  return str.slice(0, i);
}

Explanation

Supports truncating strings by character count and byte count.

More JavaScript Snippets