Skip to content

Instantly share code, notes, and snippets.

@gjcourt
Created January 5, 2011 02:49
Show Gist options
  • Save gjcourt/765850 to your computer and use it in GitHub Desktop.
Save gjcourt/765850 to your computer and use it in GitHub Desktop.
javascript translation of Benjamin Thomas' ruby code
/*
truncate text within HTML
does not work with malformed html
*/
function html_truncate(elem, num_words, truncate_string) {
// local state
var original = elem,
current = elem.childNodes[0],
count = 0;
// traverse for text nodes
while (current !== null) {
// text node
if (current.nodeType == 3) { // nodeType of 3 is text
count += current.nodeValue.split(' ').length;
// KLUDGE: figure out a way to remove leading/trailing whitespace
if (count > num_words) {
break;
}
}
// walk over other nodes
if (current.childNodes.length > 0) {
current = current.childNodes[0];
}
else if (current.nextSibling !== null) {
current = current.nextSibling;
}
else {
var n = current;
while (n.parentElement.nextSibling === null && n !== original) {
n = n.parentElement;
}
if (n == original) {
current = null;
}
else {
current = n.parentElement.nextSibling;
}
}
}
// once the limit has been reached
if (count >= num_words) {
// truncate current text node
var new_content = current.nodeValue.split(' ');
new_content = new_content.slice(0, new_content.length - (count - num_words) + 1);
// replace text
if (current.nodeType === 3) {
current.nodeValue = new_content.join(' ') + truncate_string;
}
// remove all succeeding nodes after limit
while (current !== original) {
while (current.nextSibling !== null) {
current.nextSibling.parentElement.removeChild(current.nextSibling);
}
current = current.parentElement;
}
}
}
@gjcourt
Copy link
Author

gjcourt commented Jan 5, 2011

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