Created
April 29, 2012 06:55
-
-
Save solotimes/2537334 to your computer and use it in GitHub Desktop.
javascript truncate filename
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
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 |
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 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This fails if the file doesn't have any extension.