15

Lets say we have a <div style="width:100px;">This text is too long to fit</div>

The text in the div is dynamic. And I'd like to force the text to fit in width and not break. So i need some kind of functionality to test if the text is going to fit, and if it is not, then i'd like to display the portion of the text that will actually fit. And append ...to the end.

Result for a too long text should be something like this: "This text is..."

Is there some standard way of doing what i want? Either by javascript, jquery, jsp or java?

Thanks!

Edit: Thanks for your quick and many answers! I was doing this in java by guessing how many characters would fit. It seemed like a less than optimal solution, so thats why i came here.

The css solution is perfect for me. Its not that big of a deal that it doesnt work for firefox, since my clients all use ie anyway. :)

user829237
  • 1,719
  • 8
  • 37
  • 61
  • 1
    you could even use css http://stackoverflow.com/questions/802175/truncating-long-strings-with-css-feasible-yet – sod Aug 25 '11 at 20:36

10 Answers10

34

you could do it with css3 using text-overflow:ellipsis http://www.css3.com/css-text-overflow/

or if you insist on using the js way, you can wrap the text-node inside your div and then compare the width of the wrap with the with of the parent.

meo
  • 30,872
  • 17
  • 87
  • 123
8

If you want to process the data you can use a function:

function TextAbstract(text, length) {
    if (text == null) {
        return "";
    }
    if (text.length <= length) {
        return text;
    }
    text = text.substring(0, length);
    last = text.lastIndexOf(" ");
    text = text.substring(0, last);
    return text + "...";
}

text = "I am not the shortest string of a short lenth with all these cows in here cows cows cows cows";

alert(TextAbstract(text,20));

EDIT: process all div with excess length in the text:

    var maxlengthwanted=20;

    $('div').each(function(){
        if ($('div').text().length > maxlengthwanted)
            $(this).text(TextAbstract($(this).text()));
    });

EDIT: More compact version to process all div with excess length in the text, breaks on space.

function textAbstract(el, maxlength = 20, delimiter = " ") {
  let txt = $(el).text();
  if (el == null) {
    return "";
  }
  if (txt.length <= maxlength) {
    return txt;
  }
  let t = txt.substring(0, maxlength);
  let re = /\s+\S*$/;
  let m = re.exec(t);
  t = t.substring(0, m.index);
  return t + "...";
}

var maxlengthwanted = 23;

$('.makeshort').each(function(index, element) {
  $(element).text(textAbstract(element, maxlengthwanted, " "));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="makeshort">This is a fun thing to process, modification of this is going to just be soo much fun</div>
<div class="makeshort">second This is a fun thing to process, modification of this is going to just be soo much fun</div>
<div class="makeshort">IBShort Wilson</div>
<div class="makeshort">another This is a fun thing to process, modification of this is going to just be soo much fun</div>
<div class="makeshort">more This is a fun thing to process, modification of this is going to just be soo much fun</div>
<span class="makeshort">Me also, a span that is a fun thing to process, modification of this is going to just be soo much fun</span>
<span class="makeshort">more This is a fun thing to process, modification of this is going to just be soo much fun</span>
<ul>
  <li class="makeshort">li1 more This is a fun thing to process, modification of this is going to just be soo much fun</li>
  <li class="makeshort">li 2 more This&#10;is a&#10;fun thing to process, modification of this is going to just be soo much fun</li>
  <li class="makeshort">li 3 also more&#20;This&#09;is&#09;a fun thing to process, modification of this is going to just be soo much fun</li>
  <li class="makeshort">li 4 also more This&nbsp;is&nbsp;fun thing to process, modification of this is going to just be soo much fun</li>
</ul>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
6
if(text.length > number_of_characters) {
   text = text.substring(from, to);
}
evilone
  • 22,410
  • 7
  • 80
  • 107
4

One liner using JavaScript

The below truncates the string to 10 characters with an ellipsis. If the length of the truncated string is below the limit (10 in the example below) then no ellipsis is added to the output.

const output = "abcdefghijk".split('', 10).reduce((o, c) => o.length === 9 ? `${o}${c}...` : `${o}${c}` , '');
Dynki
  • 41
  • 1
3

Easiest way to shorten the variable using JavaScript:

function truncate(string, length){
    if (string.length > length)
        return string.substring(0,length)+'...';
    else
        return string;
};

Inspired by this answer: I want to truncate a text or line with ellipsis using JavaScript

Tuxedo Joe
  • 822
  • 6
  • 18
2

If the string is a one-liner you can use the CSS solution. If its a multiline string you need to clip, i prefer using a lightweight JS plugin called cuttr.js.

Just a minimum of code needed to get it done. You could even omit the endingoption, because the three dots are the default output.

Vanilla JS implementation:

new Cuttr('.selector', {
  length: 15,
  ending: '...'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/cuttr/1.3.2/cuttr.min.js"></script>

<div class="selector" style="width:100px;">This text is too long to fit</div>

jQuery implementation:

$('.selector').Cuttr({
  length: 15,
  ending: '...'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cuttr/1.3.2/cuttr.min.js"></script>


<div class="selector" style="width:100px;">This text is too long to fit</div>

Simply add a class to the div and init the plugin. You can read more about truncating a text or line with ellipsis on the plugins website or github page - there are multiple ways to clip the string, even without messing up HTML tags.

maxpower
  • 21
  • 2
1

text-overflow: ellipis

div {
    text-overflow:  ellipsis
}

Will be supported in FireFox 7 http://caniuse.com/#search=text-overflow

Joe
  • 80,724
  • 18
  • 127
  • 145
0

If you add an id tag to the div, you can use document.getElementById("divid").innerHTML to get the contents of the div. From there, you can use .length to get the length of the string. If the length of the string is over a certain threshold, just take a substring and append a "...".

You should try to do this server-side if you can, though. Relying on Javascript/CSS to format it correctly for the user is a less than ideal solution.

Jared Ng
  • 4,891
  • 2
  • 19
  • 18
0

Try the CSS text-overflow property.

sk.
  • 6,336
  • 5
  • 38
  • 46
0

A more likely situation is that you can't possibly know how many characters are going to fit in a dom element, given it has its own font and so on. CSS3 is not currently an option (for me anyway). So, I create a little div offscreen and keep jamming test strings into it until the width is correct:

var text = 'Try to fit this text into 100 pixels!';
var max_width = 100;

var test = document.createElement('div');
test.className = 'Same Class as your real element';  // give it the same font, etc as a normal button
test.style.width = 'auto';
test.style.position = 'absolute';
test.style.left = '-2000px';
document.body.appendChild(test);            
test.innerHTML = text;

if ($(test).width() > max_width) {

    for (var i=text.length; i >= 0; i--) {
        test.innerHTML = text.substring(0, i) + '...';
        if ($(test).width() <= max_width) {
            text = text.substring(0, i) + '...';
            break;
        }
    }
}

document.body.removeChild(test);
James
  • 20,957
  • 5
  • 26
  • 41