Albin N
Albin N

Reputation: 1401

jQuery, Get filename without the extension and then replace string

I have this code to get the file extension:

filename1 = "a.crudely_formed.document_name.jpg"         
var fileExtension = filename1.substring(filename1.lastIndexOf('.')); 

Now I need to only get the filename, without the extension. As you can see in the example file names can be wildly named by the users, that's why I have to use the lastIndexOf() method. I've searched for a method of doing this, but I found nothing.

Additionally, when I have the filename (without the extension) I need something similiar to this

$filename = strtolower(str_replace(array('  ', ' '), '-', preg_replace('/[^a-zA-Z0-9 s]/', '', trim($filename))));

Above basically means, replace all spaces with dashes and only allow a-z and A-Z characters and all numbers. In the example above for example åöä is replaced by aoa.

Any suggestions on how to do this in jQuery?

Upvotes: 7

Views: 18005

Answers (2)

Nisharg Shah
Nisharg Shah

Reputation: 19522

There is a better way to get filename and extension

fileName = 'upload.png';

If you need only filename

filename.split('.').shift();

If you need only extension

filename.split('.').pop();

Upvotes: 4

Albin N
Albin N

Reputation: 1401

Ok, to only get the filename I used this:

var output = filename1.substr(0, filename1.lastIndexOf('.')) || filename1;

To do the replacement of characters I used this:

output = output.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');

Upvotes: 18

Related Questions