Skip to content

Instantly share code, notes, and snippets.

@mflisikowski
Created June 26, 2019 11:22
Show Gist options
  • Save mflisikowski/163d161eddf2a9e28a05826aa2f65beb to your computer and use it in GitHub Desktop.
Save mflisikowski/163d161eddf2a9e28a05826aa2f65beb to your computer and use it in GitHub Desktop.
truncate text fun
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