7

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?

Albin N
  • 1,401
  • 2
  • 16
  • 27

2 Answers2

18

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, '-');
Albin N
  • 1,401
  • 2
  • 16
  • 27
4

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();
Nisharg Shah
  • 16,638
  • 10
  • 62
  • 73