Skip to content

Instantly share code, notes, and snippets.

@thathurtabit
Last active September 25, 2019 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thathurtabit/ff7d96c21c178463081869ed1d424852 to your computer and use it in GitHub Desktop.
Save thathurtabit/ff7d96c21c178463081869ed1d424852 to your computer and use it in GitHub Desktop.
Truncate Text
export const truncateText = (text, characterLimit, addEllipsis = true) => {
if (text.length <= characterLimit) {
return text
} else {
const specialChars = ['.',',','!','?','-','—',' ']
let truncatedText = text.substring(0, characterLimit)
if (addEllipsis) {
const lastTruncatedChar = () => truncatedText.charAt(truncatedText.length - 1)
const hasSpecialLastChar = () => specialChars.includes(lastTruncatedChar())
// trim off last word to prevent word splitting
truncatedText = truncatedText.substring(0, Math.min(truncatedText.length, truncatedText.lastIndexOf(' ')))
// trim off special characters if there are any
while (hasSpecialLastChar()) {
truncatedText = truncatedText.substring(0, truncatedText.length - 1)
}
truncatedText = `${truncatedText}\u2026`
}
return truncatedText
}
}
@thathurtabit
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment