Skip to content

Instantly share code, notes, and snippets.

@wookiehangover
Created February 1, 2011 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wookiehangover/805291 to your computer and use it in GitHub Desktop.
Save wookiehangover/805291 to your computer and use it in GitHub Desktop.
javascript truncate w/ respect for tags
function fitBest(str, n){
var r = /\W+\w*(?=$)/m,
s = str.slice(0, n - 1)+"\n",
t = /<\/?[^>]+>/g,
c = /\/+/g,
p = /<\/?[^>]+(?=$)/m,
e = "...",
new_str = s.slice(0, s.search(r)),
tags = new_str.match(t),
open_tags = [],
i, l, q;
if( new_str.match(p) ) {
new_str = new_str.replace(p,"");
}
i = tags.length;
while(i--){
if( c.test(tags[i]) === false ){
l = tags[i].match(/\w+/);
q = "</"+l+">";
if( ! new_str.match( q ) ){
e = ( l == "a" ) ? q+e: e+q;
}
}
}
return (str.length <= n) ? str: new_str+e;
}
@wookiehangover
Copy link
Author

here's an example of it in action: http://jsfiddle.net/wookiehangover/ZmLjA/

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