Skip to main content
Inspiring
January 6, 2024
Answered

Document name without file extension [via script]

  • January 6, 2024
  • 1 reply
  • 571 views

If possible, I would like to have the name of the document without the .jpg or .tif extension
I would just like the name
this is the starting file
thanks to who helps me

 

 

dName = activeDocument.name;alert(dName);

 

 

This topic has been closed for replies.
Correct answer Stephen Marsh

@Ciccillotto 

 

You should be able to find examples of this on the forum in any script that saves files, as it is common to strip the filename extension from the current format to replace it with another one when saving in a different format.

 

The most flexible and elegant method is via a regular expression find/replace (works with single or multiple period characters):

 

var dName = activeDocument.name.replace(/\.[^\.]+$/, '');
alert(dName);

 

Another simpler method is via a split/remove on the period character, retaining the characters on the left (presuming a "clean" filename with only a single period character):

 

var dName = activeDocument.name.split('.')[0];
alert(dName);

 

If there are multiple period characters in the filename, presume that the last period is the extension:

 

var extensionIndex = activeDocument.name.lastIndexOf(".");
if (extensionIndex != -1) {
    var dName = activeDocument.name.substr(0, extensionIndex);
    alert(dName);
} else {
    alert(activeDocument.name);
}

 

https://gist.github.com/MarshySwamp/40aefebb39e0eef2d7599ac4050490d9

1 reply

Stephen Marsh
Community Expert
Stephen MarshCommunity ExpertCorrect answer
Community Expert
January 7, 2024

@Ciccillotto 

 

You should be able to find examples of this on the forum in any script that saves files, as it is common to strip the filename extension from the current format to replace it with another one when saving in a different format.

 

The most flexible and elegant method is via a regular expression find/replace (works with single or multiple period characters):

 

var dName = activeDocument.name.replace(/\.[^\.]+$/, '');
alert(dName);

 

Another simpler method is via a split/remove on the period character, retaining the characters on the left (presuming a "clean" filename with only a single period character):

 

var dName = activeDocument.name.split('.')[0];
alert(dName);

 

If there are multiple period characters in the filename, presume that the last period is the extension:

 

var extensionIndex = activeDocument.name.lastIndexOf(".");
if (extensionIndex != -1) {
    var dName = activeDocument.name.substr(0, extensionIndex);
    alert(dName);
} else {
    alert(activeDocument.name);
}

 

https://gist.github.com/MarshySwamp/40aefebb39e0eef2d7599ac4050490d9