Created
January 28, 2023 11:59
-
-
Save gruhh/719e304c454e3b622801e51126654464 to your computer and use it in GitHub Desktop.
Truncate a string based on the number of characters before and after
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
/* | |
* 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