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.
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.
This will limit it to however many lines you want it limited to and is responsive
An idea that nobody has suggested, doing it based on the height of the element and then stripping it back from there.
Fiddle - https://jsfiddle.net/hutber/u5mtLznf/ <- ES6 version
But basically you want to grab the line height of the element, loop through all the text and stop when its at a certain lines height:
'use strict';
var linesElement = 3; //it will truncate at 3 lines.
var truncateElement = document.getElementById('truncateme');
var truncateText = truncateElement.textContent;
var getLineHeight = function getLineHeight(element) {
var lineHeight = window.getComputedStyle(truncateElement)['line-height'];
if (lineHeight === 'normal') {
// sucky chrome
return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']);
} else {
return parseFloat(lineHeight);
}
};
linesElement.addEventListener('change', function () {
truncateElement.innerHTML = truncateText;
var truncateTextParts = truncateText.split(' ');
var lineHeight = getLineHeight(truncateElement);
var lines = parseInt(linesElement.value);
while (lines * lineHeight < truncateElement.clientHeight) {
console.log(truncateTextParts.length, lines * lineHeight, truncateElement.clientHeight);
truncateTextParts.pop();
truncateElement.innerHTML = truncateTextParts.join(' ') + '...';
}
});
CSS
#truncateme {
width: auto; This will be completely dynamic to the height of the element, its just restricted by how many lines you want it to clip to
}