truncateString.js 1.0 KB

1234567891011121314151617181920212223242526
  1. "use strict";
  2. /**
  3. * Truncates a string to the given number of chars (maxLength) by inserting '...' in the middle of that string.
  4. * Partially taken from https://stackoverflow.com/a/5723274/3192470.
  5. *
  6. * @param {string} string - string to be truncated
  7. * @param {number} maxLength - maximum size of the resulting string
  8. * @returns {string}
  9. */
  10. const separator = '...';
  11. function truncateString(string, maxLength) {
  12. // Return the empty string if maxLength is zero
  13. if (maxLength === 0) return ''; // Return original string if it's already shorter than maxLength
  14. if (string.length <= maxLength) return string; // Return truncated substring appended of the ellipsis char if string can't be meaningfully truncated
  15. if (maxLength <= separator.length + 1) return `${string.slice(0, maxLength - 1)}…`;
  16. const charsToShow = maxLength - separator.length;
  17. const frontChars = Math.ceil(charsToShow / 2);
  18. const backChars = Math.floor(charsToShow / 2);
  19. return string.slice(0, frontChars) + separator + string.slice(-backChars);
  20. }
  21. module.exports = truncateString;