Skip to content

Instantly share code, notes, and snippets.

@solotimes
Created April 29, 2012 06:55
Show Gist options
  • Select an option

  • Save solotimes/2537334 to your computer and use it in GitHub Desktop.

Select an option

Save solotimes/2537334 to your computer and use it in GitHub Desktop.
javascript truncate filename
var s = 'this-is-a-very-very-very-long-file-name.jpg';
console.log(truncate(s, 100)); //this-is-a-very-very-very-long-file-name.jpg
console.log(truncate(s, 10)); //this-is-a-[...].jpg
console.log(truncate(s, 4)); //this[...].jpg
function truncate(n, len) {
var ext = n.substring(n.lastIndexOf(".") + 1, n.length).toLowerCase();
var filename = n.replace('.' + ext,'');
if(filename.length <= len) {
return n;
}
filename = filename.substr(0, len) + (n.length > len ? '[...]' : '');
return filename + '.' + ext;
};
@dbackeus
Copy link
Copy Markdown

This fails if the file doesn't have any extension.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment