Created
May 10, 2020 05:25
-
-
Save dwoodard/768fdb134d242924d67c308894a50061 to your computer and use it in GitHub Desktop.
truncate string
This file contains 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
// truncate('this is a test is a bunch of text now do some truncating') | |
// truncate('this is a test is a bunch of text now do some truncating', 50, '', '') | |
// truncate('this is a test is a bunch of text now do some truncating', 50, '', '...') | |
// truncate('this is a test is a bunch of text now do some truncating', 50, ' ', '...') | |
const truncate = (string, limit = 50, breakChar = ' ', rightPad = '...') => { | |
if (string.length <= limit) return string; | |
const breakPoint = string.substr(0, limit).lastIndexOf(breakChar); | |
if (breakPoint >= 0 && breakPoint < string.length - 1) { | |
return string.substr(0, breakPoint) + rightPad; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment