truncate-middle.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. /**
  2. * Date: 2015-10-05
  3. * Author: Kasper Søfren <soefritz@gmail.com> (https://github.com/kafoso)
  4. *
  5. * A truncation feature, where the ellipsis will be placed in the dead-center of the URL.
  6. *
  7. * @param {String} url A URL.
  8. * @param {Number} truncateLen The maximum length of the truncated output URL string.
  9. * @param {String} ellipsisChars The characters to place within the url, e.g. "..".
  10. * @return {String} The truncated URL.
  11. */
  12. export function truncateMiddle(url, truncateLen, ellipsisChars) {
  13. if (url.length <= truncateLen) {
  14. return url;
  15. }
  16. var ellipsisLengthBeforeParsing;
  17. var ellipsisLength;
  18. if (ellipsisChars == null) {
  19. ellipsisChars = '&hellip;';
  20. ellipsisLengthBeforeParsing = 8;
  21. ellipsisLength = 3;
  22. }
  23. else {
  24. ellipsisLengthBeforeParsing = ellipsisChars.length;
  25. ellipsisLength = ellipsisChars.length;
  26. }
  27. var availableLength = truncateLen - ellipsisLength;
  28. var end = '';
  29. if (availableLength > 0) {
  30. end = url.substr(-1 * Math.floor(availableLength / 2));
  31. }
  32. return (url.substr(0, Math.ceil(availableLength / 2)) + ellipsisChars + end).substr(0, availableLength + ellipsisLengthBeforeParsing);
  33. }
  34. //# sourceMappingURL=truncate-middle.js.map