Skip to content

Instantly share code, notes, and snippets.

@zaaack
Last active September 21, 2016 01:51
Show Gist options
  • Save zaaack/cc3a806cccde1cca57708370c311d7f7 to your computer and use it in GitHub Desktop.
Save zaaack/cc3a806cccde1cca57708370c311d7f7 to your computer and use it in GitHub Desktop.
safe truncate html, without broken any tags
function truncHtml(html, truncNum) {
if (!truncNum) {
return 0
}
let sum = 0, index = 0
;('>'+html+'<').replace(/>([^<>]*)</g, (ma, g1, offset, str) => {
g1 = g1.trim()
if (sum - 1 < truncNum && sum + g1.length - 1 >= truncNum) {
index = offset + (truncNum - sum) - 1
console.log(index, offset, sum)
}
sum += g1.length
return ''
})
truncNum = index
const truncated = html.substring(0, truncNum)
const removed = html.substring(truncNum)
const reserved = removed
.replace(/>[^<>]*</g, '><')
.replace(/^[^<>]*</, '<')
.replace(/>[^<>]*$/, '>')
.replace(/<br[/]?>/g, '')
.replace(/<img[^>]*>/g, '')
.replace(/<div[^>]*><\/div>/g, '')
return truncated + reserved
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment