Created
January 5, 2011 02:49
-
-
Save gjcourt/765850 to your computer and use it in GitHub Desktop.
javascript translation of Benjamin Thomas' ruby code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ruby code is here: http://benjaminthomas.org/2009-01-30/smart-html-truncate.html