Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short down text, but leave the filetype visible

Tags:

jquery

text

short

How can I make this possible?

From this-is-a-very-long-filename.jpg to this-is-a-very-lo [...] .jpg.

I have searched Google for several minutes now but I can't find any solution to this. Do you know how I can do this?

Thanks in advance!

like image 564
Airikr Avatar asked Nov 29 '11 01:11

Airikr


1 Answers

You don't really need jQuery for this, you can use classic javascript:

<script>
  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;
  };
  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
</script>
like image 119
Book Of Zeus Avatar answered Sep 30 '22 07:09

Book Of Zeus