Skip to content

Instantly share code, notes, and snippets.

@jeremyckahn
Created August 15, 2011 22:29
Show Gist options
  • Save jeremyckahn/1148041 to your computer and use it in GitHub Desktop.
Save jeremyckahn/1148041 to your computer and use it in GitHub Desktop.
Lets you limit the length of the string and truncate the end with ellipses (...).
/**
* Lets you limit the length of a string and truncate the end with ellipses (...).
*
* @param {String} str The String to truncate.
* @param {Number} limit The maximum size of the string.
*/
function truncateWithEllipsis (str, limit) {
var truncatedString;
limit -= 3;
if (str.length > limit) {
truncatedString = str.substr(0, limit);
truncatedString = truncatedString.replace(/\s+(\S*)$/, '...');
} else {
truncatedString = str;
}
return truncatedString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment