JQuery: shorten the length of a string so that it matches the specified width

I have a table, and in each cell I want to place the rows, but they are much wider than the width of the cell. To prevent line breaks, I would like to cut the lines to fit the cell and add β€œ...” to the end to indicate that the line is much longer.

A table has about 40 rows and needs to be done for each cell, so it is important that it is fast. Should I use JS / jQuery for this?

How can I do it?

Thank you for your time.

Yours faithfully,
Marius

+6
javascript jquery string
source share
3 answers

You can use CSS-text-overflow: ellipsis - for this - with some caveats for specific browsers and workarounds listed here:

http://mattsnider.com/css/css-string-truncation-with-ellipsis/(in the archive)

+8
source share

this should do the trick where 8 is the size of the text you want to keep

$('td').each(function(){ $(this).text($(this).text().substring(0,8)+"..."); }); 

to respond to your comment. I think jquery width () should help you with this, but I think you headed a slippery slope that you should consider something else, like putting text in a div or using flexigrid or jgrid

+4
source share

Use my jQuery plugin: jQuery-Shorten. . It handles all cases, uses a text stream: an ellipsis, if available, and very fast.

Download: github.com/MarcDiethelm/jQuery-Shorten

Demo and Doc: http://web5.me/jquery/plugins/shorten/shorten.doc.html

You can customize how the text ends (ellipsis). The default is a three-point char ("...", & hellip ;, Unicode: 2026), but you can use whatever you want, including markup.

The width of the text of the "selected" element (for example, span or div) is measured using Canvas or by placing it in a temporary cell of the table and is reduced (initially using a reasonable assumption of efficiency) and measured again until it (and the added ellipsis or text ) is placed inside the block. The tooltip on the "selected" element displays the full source text.

+4
source share

All Articles