Damian_B
Damian_B

Reputation: 75

How to trim name of selected file with JS?

I have little JS script for input file name:

$('#e-file-reset').on('click', function(e) {
  var $el = $('#e-file-upload');
  $el.wrap('<form>').closest('form').get(0).reset();
  $el.unwrap();
  $("#e-file-name").text("");
});

and it's shows name of selected file. Now I want trim this name, but only name, without extension, so: from filename.mp4 I want trim to eg. filena....mp4. How should I do it?

Upvotes: 1

Views: 409

Answers (1)

Petar Vasilev
Petar Vasilev

Reputation: 282

You can split the filename to get the name and extension, trim the name and append the extension again. For example:

function trimFileName(fileName){
    var delimiter = fileName.lastIndexOf('.'), // fileName hold the whole name filename.ml4
        extension = fileName.substr(delimiter), // the extension of the file
        file = fileName.substr(0, delimiter); // just the name of the file

    var filenameLen = 6; // adjust for the required filename length
    return (file.length > filenameLen ? file.substr(0, filenameLen) + "..." : file) + extension;
}

Hope this is what you had in mind.

Upvotes: 1

Related Questions