Created
June 26, 2019 11:22
-
-
Save mflisikowski/163d161eddf2a9e28a05826aa2f65beb to your computer and use it in GitHub Desktop.
truncate text fun
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
const truncateText = ( | |
str, | |
len = 42, | |
end = '...', | |
words = true, | |
regex = /[-.*+?^${}()|[\]\\]/g, | |
after = ' ', | |
) => { | |
const replaced = str.replace(regex, ''); | |
const string = replaced.substr(0, len); | |
const length = string.length; | |
const index = Math.min(length, string.lastIndexOf(after)); | |
const shortened = `${string.substr(0, words ? index : length)} ${end}`; | |
return shortened; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment