Home > InDesign Scripts > Extract File Name and Extension

Extract File Name and Extension

This is short and simple. Fast way to extract file name (without extension) and extension from file. Unfortunately Javascript doesn’t allow us to retrieve just file name or extension, but we can achieve it in really simple way through string operations. We are going to create simple prototype for ‘file();’ class. So, let’s get started! 😀

What we have to do is to find position of last dot in file and then pass part from beginning to dot that we found like file name, and part after dot like extension. There are two ways to do that. First is to use ‘substr();’ method to extract part of string and ‘lastIndexOf();’ to find dot. Second is to use ‘replace();’ method in combination with regular expression.

First let’s declare example file:

var myFile = File("/c/myWorks/myTestFile_with-multiple.dots.xml");

Good, now we can take look how to use First method:

var myFileName = myFile.name.substr(0,myFile.name.lastIndexOf("."));
var myFileExt = myFile.name.substr(myFile.name.lastIndexOf(".") + 1,myFile.name.length);

Second method

What this will do, to extract file name, is to locate the last dot and delete all after, and for extension will find all to the last dot end delete it.

var myFileName = myFile.name.replace(/.[^.]+$/,'');
var myFileExt = myFile.name.replace(/^.*\./,'');

And at the end, we can implement this methods into the ‘File’ prototype and use them very easily. We will use second method:

File name:

File.prototype.fileName = function(){
    return this.name.replace(/.[^.]+$/,'');


File.prototype.fileExt = function(){
    return this.name.replace(/^.*\./,'');

Now we can use extracting like this:

var myFileName = myFile.fileName();

var myFileExt = myFile.fileExt();

That’s it!

Have fun! 😀

  1. Daniel
    March 30, 2011 at 03:04

    Hey Marjan,

    Thanks for this–it really helps in a little coding project. I’m still new to JS, though & am not sure how to use .prototype to add to the File object. Do you just add File.prototype.fileName = function(){return this.name.replace(/.[^.]+$/,”);} at the end of your script as another function or must it be initialized somewhere? I’m a little fuzzy on the concept. Thanks for any further education you can lend…

  2. Daniel
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: