How Do I Add Ellipses to Text

570 views Asked by At

I am trying to create a function that will take an element's text, cut off any characters beyond 80, and add an ellipses if necessary. Here's my code so far:

var maxLength = 80;
function shorten(element) {
  var text = $('#' + element).text();
  var ret = text;
  if (text.length > maxLength) {
    text = text.substr(0,maxLength-3) + "...";
  }
$('#' + element).text(text);
}
shorten('slide1');

So, the function should take the element, remove extra text off the end, add an ellipses, and then replace the old text in the element with the new string I've just created.

When I run the function, I don't get any errors, but it doesn't actually cut off the text as it should. Why is this?

1

There are 1 answers

0
AndrewTet On BEST ANSWER
var text = "Some Text Goes Here. La La La La!";
var textLength = 10; // Number of characters to cut off after

function shorten(text, textLength){
    if(text.length > textLength){
        text = text.substring(0, textLength) + '…';
    }
    return text;
}

var shortText = shorten(text, textLength);

Also, using the HTML character for ellipsis is better than using three periods.

I've added a Codepen showing the code working. Additionally, I added a function spaceShorten that will split your text at the last occurrence of a space that is less than the length provided, so you don't split the text mid word.

http://codepen.io/supah_frank/pen/EaYzNz