Search code examples
jquerytextshort

Short down text, but leave the filetype visible


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!


Solution

  • 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>