Skip to content

Instantly share code, notes, and snippets.

@kevinsalter
Last active July 19, 2022 19:49
Show Gist options
  • Save kevinsalter/dd176d847cecb4c4d4b30c9bc4dfd17e to your computer and use it in GitHub Desktop.
Save kevinsalter/dd176d847cecb4c4d4b30c9bc4dfd17e to your computer and use it in GitHub Desktop.
/**
* ellipsisify
* @param {string} filename - The filename to be truncated.
* @param {number} lengthThreshold - (optional) The minimum length of filename to truncate.
*/
export const ellipsisify = (filename, lengthThreshold = 20) => {
// just return the filename if it's less than 20 characters long
if (filename.length < lengthThreshold) return filename;
// calculate a reasonable value for `sideLength` which will represent
// the number of characters on either side of the … (&hellip;) character
// (not including the final dot and extension name)
const sideLength = Math.floor(lengthThreshold / 2.5);
// break the filename into 2 (or more) pieces, creating a new array
// i.e. [‘whoa-this-is-a-crazy-long-filename’, ‘png’]
const filenamePieces = filename.split('.');
// capture the last element of the array (the extension) into a variable
const extension = filenamePieces.pop();
// with `filenameBeforeExtension` we’re making sure that we take all the pieces of the array except
// the last piece, and gluing them back together if necessary. In our example it doesn’t matter,
// but if the filename were something like `whoa.this.is.a.crazy.long.filename.png`
// then we would have gotten an array like this in the previous step
// [‘whoa’, ‘this’, ‘is’, ‘a’, ‘crazy’, ‘long’, ‘filename’, ‘png’], therefore
// we’d have to join all of those pieces back together and restore the dots as well
const filenameBeforeExtension = filenamePieces.slice(0, filenamePieces.length).join('.');
// now that we’ve got our final filename string (without the extension) we want the first number
// of letters (the value of `sideLength`) and the last letters to be captured in their own variables
const firstLetters = filenameBeforeExtension.substring(0, sideLength);
const lastLetters = filenameBeforeExtension.substring(filenameBeforeExtension.length - sideLength);
// finally, glue it all back together and return the final string!
return `${firstLetters}…${lastLetters}.${extension}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment