Skip to content

Instantly share code, notes, and snippets.

@peeke
Last active March 22, 2017 12:45
Show Gist options
  • Save peeke/713b826d5de43b4dfc6c5dd1c58087cf to your computer and use it in GitHub Desktop.
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.
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