Last active
September 16, 2016 15:12
-
-
Save tannerhodges/c0f5e55abb7c426828d03eee50b7c1e7 to your computer and use it in GitHub Desktop.
Shorten long text, add ellipsis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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