Skip to content

Instantly share code, notes, and snippets.

@tannerhodges
Last active September 16, 2016 15:12
Show Gist options
  • Save tannerhodges/c0f5e55abb7c426828d03eee50b7c1e7 to your computer and use it in GitHub Desktop.
Save tannerhodges/c0f5e55abb7c426828d03eee50b7c1e7 to your computer and use it in GitHub Desktop.
Shorten long text, add ellipsis
/**
* Shorten long text, add ellipsis.
* @param {String} text
* @param {Number} maxLength
* @return {String}
*/
function shorten(text, maxLength) {
maxLength = maxLength || 220;
if (text.length <= maxLength) {
return text;
}
text = text.substr(0, maxLength);
// If text ends in whitespace, trim
if (/^\S/.test(text.substr(maxLength))) {
text = text.replace(/\s+\S*$/, '');
}
// Remove trailing punctuation
text = text.replace(/[^a-zA-Z]+$/, '');
return text + '...';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment