Created
November 10, 2022 07:42
-
-
Save nwingt/6173157bf66227f68ed655b6cb8bc033 to your computer and use it in GitHub Desktop.
Shorten String
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
function shortenString(s, limit = 15, skippedReplacer = '...') { | |
if (!s || s.length <= limit) return s; | |
const trimmedLength = | |
Math.max(limit, skippedReplacer.length + 2) - skippedReplacer.length; | |
const chunkLength = Math.floor(trimmedLength / 2); | |
const [head, tail] = [ | |
s.substring(0, chunkLength + (trimmedLength % 2)), | |
s.substring(s.length - chunkLength, s.length), | |
]; | |
return `${head}${skippedReplacer}${tail}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment