Skip to content

Instantly share code, notes, and snippets.

@ChrisCinelli
Last active July 1, 2016 07:11
Show Gist options
  • Select an option

  • Save ChrisCinelli/5688048 to your computer and use it in GitHub Desktop.

Select an option

Save ChrisCinelli/5688048 to your computer and use it in GitHub Desktop.
Javascript: Truncate a paragraph to maxLength characters. It does not break a single words. ellipseText is optional (default: … ) It will not work on characters that are not a letter A-Z or number. It backtracks until there is a space and add the ellipseText.
function truncText (text, maxLength, ellipseText){
ellipseText = ellipseText || '…';
if (text.length < maxLength)
return text;
//Find the last piece of string that contain a series of not A-Za-z0-9_ followed by A-Za-z0-9_ starting from maxLength
var m = text.substr(0, maxLength).match(/([^A-Za-z0-9_]*)[A-Za-z0-9_]*$/);
if(!m) return ellipseText;
//Position of last output character
var lastCharPosition = maxLength-m[0].length;
//If it is a space or "[" or "(" or "{" then stop one before.
if(/[\s\(\[\{]/.test(text[lastCharPosition])) lastCharPosition--;
//Make sure we do not just return a letter..
return (lastCharPosition ? text.substr(0, lastCharPosition+1) : '') + ellipseText;
}
@diegofer
Copy link
Copy Markdown

this work for me, thank you

@kidlab
Copy link
Copy Markdown

kidlab commented Jul 1, 2016

Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment