Last active
February 10, 2021 18:25
-
-
Save FelipeGangrel/74a919be34ef42ed069d9d4312f12071 to your computer and use it in GitHub Desktop.
getHtmlExcerpt.js
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
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