Skip to content

Instantly share code, notes, and snippets.

@dwoodard
Created May 10, 2020 05:25
Show Gist options
  • Save dwoodard/768fdb134d242924d67c308894a50061 to your computer and use it in GitHub Desktop.
Save dwoodard/768fdb134d242924d67c308894a50061 to your computer and use it in GitHub Desktop.
truncate string
// 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