Truncate your ... strings!

Geschreven op 19 juni 2018 door Jordi Fuite

Truncating strings might cause headaches for some developers. For some, it's just a piece of cake.

Sometimes the end of a string is more important than the beginning of a string. So... How do we truncate those strings? Our idea was to truncate the strings from the middle, so we have both the beginning and end available. Quite easy, right? But how about a word safe truncate with an ellipsis in the middle? And what if we don't want to fit the new string to a special amount of characters but to a width in pixels?

Our strings will end up like this:
Lorem ipsum dolor sit ... ipsa praesentium dolore adipisci?

But how?! Just look at these functions and you'll understand. If not, just copy them.

  /**
   * Truncate the text and add an ellipsis in middle of the string.
   */
  function truncateByWord(str, length, ellipsis) {
    var words = str.split(/\b/);
    var left = [];
    var right = [];
    var outLength = ellipsis.length;
    var word;
    while (words) {
      word = words.shift();
      if (outLength + word.length > length) {
        break;
      }
      left.push(word);
      outLength += word.length;
      word = words.pop();
      if (outLength + word.length > length) {
        break;
      }
      right.unshift(word);
      outLength += word.length;
    }

    return left.join('') + ellipsis + right.join('');
  }

  /**
   * Truncate the element by a width in pixels
   */
  $.fn.truncateByWidth = function(width) {
    var $element = $(this);
    var element = $element[0];
    var text = $element.text();

    var currentStyle = element.currentStyle || window.getComputedStyle(element, '');

    // We need an inline element for truncating.
    // So create an inline element if the element is not an inline element.
    if (currentStyle.display !== 'inline') {
      var $span = $('<span />').addClass('truncater').text(text);
      $element.html($span);
      $element = $span;
    }

    for (var i = text.length; i > 0; i--) {
      $element.text(truncateByWord(text, i, ' ... '));
      if ($element.width() < width) {
        break;
      }
    }
  };

Reactie toevoegen

Plaats hier uw naam.