Last active
          September 25, 2019 12:58 
        
      - 
      
- 
        Save thathurtabit/ff7d96c21c178463081869ed1d424852 to your computer and use it in GitHub Desktop. 
    Truncate Text
  
        
  
    
      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 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 | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Example at: https://codepen.io/thathurtabit/pen/rNBMrRX