Last active
September 21, 2016 01:51
-
-
Save zaaack/cc3a806cccde1cca57708370c311d7f7 to your computer and use it in GitHub Desktop.
safe truncate html, without broken any tags
This file contains 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
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