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.
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.
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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With