Skip to content

Instantly share code, notes, and snippets.

@nwingt
Created November 10, 2022 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwingt/6173157bf66227f68ed655b6cb8bc033 to your computer and use it in GitHub Desktop.
Save nwingt/6173157bf66227f68ed655b6cb8bc033 to your computer and use it in GitHub Desktop.
Shorten String
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