How to replace part of a line with a width of more than 50 pixels by "..."?

I am looking for a function that replaces part of a line with a width of more than 50 pixels with "..." . I want to implement it in Javascript / jQuery.

Example:

  • Say I have a var="Theta Saving Non-Qualified Plan"; variable var="Theta Saving Non-Qualified Plan"; I want to limit the length of the string (based on the width of the pixel). If the line length is more than 50px, then the part of the line that is from the 51st pixel to the end of the line will be replaced by "..." .

Any ideas guys?

+4
source share
5 answers

Do not try to reinvent the wheel. Use the jQuery plugin as follows: http://tpgblog.com/2009/12/21/threedots-the-jquery-ellipsis-plugin/

+2
source

Here is the solution if you want to trim the visual code and don't need to trim the actual string:

 <p> <span style='width: 50px; height: 1em; overflow: hidden; display: inline-block'> This is the long string which should appear truncated followed by elipses </span> <span>...</span> </p> 

To make it work in IE6 and 7, I think you need to add the following CSS:

 zoom: 1 *display: inline; 
+1
source

It is impossible to deduce as simple as we would like. Since the width of a character or character set will depend on the font size. And calculating the width of the text is hardly accurate.

So, the better you create your interface to be character-friendly, not width-wise.

 var t = $("#div").text(); if(t.length > 50) { $("#div").text(t.substr(0,50)+"..."); } 
0
source

I would split the string in the array and then add the letter after the letter, checking the width of the element to see if it is less than 50px

those.:

 var vElement = $('.your_element'); var vStr = vElement.html(); var vShortStr = ""; var vArray = vStr.split(""); for (var i=0; i<vArray.length; i++){ vShortStr += vArray[i]; vElement.html(vShortStr); if(vElement.width() > 50){ vShortStr = vShortStr.substring(0, vShortStr.length-1); vShortStr += "..."; vElement.html(vShortStr); break; } }​ 
0
source

If your text is already enclosed in a block element with a width of 50 pixels, you can use the CSS text-overflow rule, which is widely supported by almost all browsers. Also see text overflow in quirksmode .

0
source

Source: https://habr.com/ru/post/1414571/


All Articles