Last active
March 22, 2017 12:45
-
-
Save peeke/713b826d5de43b4dfc6c5dd1c58087cf to your computer and use it in GitHub Desktop.
Trim arbitrary html code based on word count. To be used in conjuction with .innerHTML, so unclosed tags are closed automatically.
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
const trim = (html, wordCount = 16) => { | |
const wordsAndTags = /<(.|\n)*?>|[^\s\<]+/g; | |
const tag = /<(.|\n)*?>/; | |
return html | |
.match(wordsAndTags) | |
.reduce((result, match) => { | |
if (!wordCount) return result; | |
const isTag = tag.test(match); | |
isTag && wordCount--; | |
return result + match + (isTag ? '' : ' '); | |
}, ''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment