Skip to content

Instantly share code, notes, and snippets.

@tbeseda
Created January 6, 2011 00:09
Show Gist options
  • Select an option

  • Save tbeseda/767275 to your computer and use it in GitHub Desktop.

Select an option

Save tbeseda/767275 to your computer and use it in GitHub Desktop.
truncate a string to a set number of chars and add ellipses with respect for non-word characters.
function fit(str, nMaxChars) {
var n = nMaxChars - 1,
strRX = /\s|\.|,/,
tmp_str = str.slice(0, n),
final_str;
if (str.length <= n) return str;
function getLastChar(str) {
return str.slice(str.length-1, str.length);
}
function trimLastChar(str) {
return str.slice(0, str.length - 1);
}
(function isLast(lstr){
var lastChar = getLastChar(lstr),
short_str = trimLastChar(lstr),
short_lastChar = getLastChar(short_str);
if( strRX.test(lastChar) ) {
final_str = ( /\W/.test(short_lastChar) ) ? trimLastChar(short_str) : short_str;
final_str += "...";
} else {
isLast(short_str);
}
})(tmp_str);
return final_str;
}
@wookiehangover
Copy link

I made a shorter version :)

function fitBetter(str, n){
    var r = /(\s|\W)+(?=\n)/m,
         s = str.slice(0, n - 1)+"\n";    
    return s.slice(0, s.search(r))+"...";
}

http://jsfiddle.net/wookiehangover/VTPta/

@tbeseda
Copy link
Author

tbeseda commented Jan 6, 2011

Badass. Adding to my snippets lib.
But it doesn't respect word breaks: http://jsfiddle.net/tbeseda/H5Hsk/1/

@wookiehangover
Copy link

@tbeseda
Copy link
Author

tbeseda commented Jan 6, 2011

Just one thins. Needed to check the length to see if it was already <= n

if(str.length <= n) return str;

http://jsfiddle.net/tbeseda/VTPta/3/

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