Copy link to clipboard
Copied
I am using this script to add filename as a layer. How to I get it to leave off the last chacter of file
example my file is called L10100-1A and want the added layer filename to be L10100-1
if ( documents.length > 0 )
{
var originalDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.ERROR;
var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.PIXELS;
try
{
var docRef = activeDocument;
// Now create a text layer at the front
var myLayerRef = docRef.artLayers.add();
myLayerRef.kind = LayerKind.TEXT;
myLayerRef.name = "Filename";
var myTextRef = myLayerRef.textItem;
// strip the extension off
var fileNameNoExtension = docRef.name;
fileNameNoExtension = fileNameNoExtension.split( "." );
if ( fileNameNoExtension.length > 1 ) {
fileNameNoExtension.length--;
}
fileNameNoExtension = fileNameNoExtension.join(".");
myTextRef.contents = fileNameNoExtension;
// off set the text to be in the middle
myTextRef.position = new Array( docRef.width / 2, docRef.height / 2 );
myTextRef.size = 20;
}
catch( e )
{
// An error occurred. Restore ruler units, then propagate the error back
// to the user
preferences.rulerUnits = originalRulerUnits;
app.displayDialogs = originalDialogMode;
throw e;
}
// Everything went Ok. Restore ruler units
preferences.rulerUnits = originalRulerUnits;
app.displayDialogs = originalDialogMode;
}
else
{
alert( "You must have a document open to add the filename!" );
Copy link to clipboard
Copied
Change statement that sets the text layer content to what you want
myTextRef.contents = fileNameNoExtension;
Copy link to clipboard
Copied
Thank you.
Copy link to clipboard
Copied
After you strip the extension you could use a substr function to remove the last character
fileNameNoExtension = fileNameNoExtension.join(".");
fileNameNoExtension = fileNameNoExtension.substr(0, fileNameNoExtension.length-1);
Copy link to clipboard
Copied
Thank you!
Copy link to clipboard
Copied
Another option is a regular expression find/replace:
var removeTrailingCharacter = fileNameNoExtension.replace(/.$/, '');
myTextRef.contents = removeTrailingCharacter;
P.S. The original code posting is missing a closing brace character on the last line }
Copy link to clipboard
Copied
Another option...
var layerName = decodeURI(app.activeDocument.name).replace(/.\.[^\.]+$/, '');
Copy link to clipboard
Copied
Using .split (".") Is not the best choice, as the filename may contain a dot not only at the end of the line, but also in the name itself. I am in favor of regular expressions, or a faster option .lastIndexOf ('.')