Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to truncate a text or line with ellipsis using JavaScript [closed]

I'm looking for a simple script which can truncate a string with ellipsis (...)

I want to truncate something like 'this is a very long string' to 'this is a ve...'

I don't want to use CSS or PHP.

like image 895
Dollar Friend Avatar asked Jan 15 '11 14:01

Dollar Friend


People also ask

How do you truncate a paragraph in JavaScript?

JavaScript Code: text_truncate = function(str, length, ending) { if (length == null) { length = 100; } if (ending == null) { ending = '...'; } if (str. length > length) { return str. substring(0, length - ending. length) + ending; } else { return str; } }; console.

How do I text-overflow ellipsis?

To clip at the transition between characters you can specify text-overflow as an empty string, if that is supported in your target browsers: text-overflow: ''; . This keyword value will display an ellipsis ( '…' , U+2026 HORIZONTAL ELLIPSIS ) to represent clipped text.

How do I truncate a paragraph in HTML?

We can achieve this by setting a whitespace property to the nowrap value. The text-overflow property specifies how overflowed content that is not displayed should be signaled to the user. It can be cropped, show ellipsis (. In step 1, we'll create an HTML element to place the text we want to truncate inside.


2 Answers

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

or in ES6

const truncate = (input) => input.length > 5 ? `${input.substring(0, 5)}...` : input; 
like image 77
El Ronnoco Avatar answered Sep 18 '22 16:09

El Ronnoco


KooiInc has a good answer to this. To summarise:

String.prototype.trunc =        function(n){           return this.substr(0,n-1)+(this.length>n?'…':'');       }; 

Now you can do:

var s = 'not very long'; s.trunc(25); //=> not very long s.trunc(5); //=> not... 

And if you prefer it as a function, as per @AlienLifeForm's comment:

function truncateWithEllipses(text, max)  {     return text.substr(0,max-1)+(text.length>max?'…':'');  } 

Full credit goes to KooiInc for this.

like image 31
Jarrod Avatar answered Sep 16 '22 16:09

Jarrod