Skip to content

Instantly share code, notes, and snippets.

@marinabearman
Last active August 2, 2018 00:12
Show Gist options
  • Save marinabearman/6e8144c20eb10b8d481fceb0b95727a4 to your computer and use it in GitHub Desktop.
Save marinabearman/6e8144c20eb10b8d481fceb0b95727a4 to your computer and use it in GitHub Desktop.
multiline truncation with JS
<div class="ellipsis"></div>
const limitTitle = (title, limit = 150) => {
// const is correc. We are mutating the array which is stored in the const
// same is true of objects
const newTitle = [];
if (title.length > limit) {
//split title on it's words
//reduce method on resulting array
//allows for accumulator variable that we can add to in each iteration of the loop where we test if the current title is still under maximum link
title.split(' ').reduce((acc, cur) => {
if (acc + cur.length <= limit) {
newTitle.push(cur);
}
return acc + cur.length;
}, 0);
//return result
return `${newTitle.join(' ')} ...`
}
return title;
};
let title =`<p style="width:20%;">Lorem ipsum dolor amet tbh listicle vinyl, normcore lumbersexual wayfarers swag. Hashtag cliche readymade gochujang narwhal austin, ramps etsy fingerstache woke. PBR&B single-origin coffee everyday carry, tumeric ramps franzen sriracha kogi aesthetic cred authentic fingerstache. Man braid subway tile pork belly lo-fi kinfolk. Ugh stumptown +1 bicycle rights distillery truffaut, selvage chambray adaptogen before they sold out artisan vegan. Selvage cliche truffaut celiac leggings whatever.</p>`
document.querySelector('.ellipsis').innerHTML =limitTitle(title, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment