Skip to content

Instantly share code, notes, and snippets.

@gruhh
Created January 28, 2023 11:59
Show Gist options
  • Save gruhh/719e304c454e3b622801e51126654464 to your computer and use it in GitHub Desktop.
Save gruhh/719e304c454e3b622801e51126654464 to your computer and use it in GitHub Desktop.
Truncate a string based on the number of characters before and after
/*
* Middle Truncate Text
*
* Example: middleTruncateText('123456789', 3), returns "123...789"
*
* @param {string} text - The text to be truncated
* @param {number} visibleSize - Number of chars on each side (default 5)
* @param {string} ellipsis - The string to place on truncated text (default '...')
*/
export const middleTruncateText: (
text: string,
visibleSize?: number,
ellipsis?: string
) => string = (text, visibleSize = 5, ellipsis = '...') => {
if ((visibleSize * 2) + ellipsis.length > text.length)
return text;
return text.substring(0, visibleSize) + ellipsis + text.substring(text.length - visibleSize)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment