Skip to content

Instantly share code, notes, and snippets.

@FelipeGangrel
Last active February 10, 2021 18:25
Show Gist options
  • Save FelipeGangrel/74a919be34ef42ed069d9d4312f12071 to your computer and use it in GitHub Desktop.
Save FelipeGangrel/74a919be34ef42ed069d9d4312f12071 to your computer and use it in GitHub Desktop.
getHtmlExcerpt.js
export function getExcerpt(htmlString, length) {
const span = document.createElement("span");
span.innerHTML = htmlString;
const outputString = span.textContent || span.innerText;
if (outputString.length > length) {
// obtendo os *length* primeiros caracteres sem quebrar palavras
// usando flag s para tratar a string como single line
const exp = new RegExp(`^(.{${length}}[^\\s]*).*`, "s");
return outputString.replace(exp, "$1...");
}
return outputString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment