Skip to main content
Participating Frequently
July 29, 2020
質問

How to add filename

  • July 29, 2020
  • 返信数 4.
  • 2491 ビュー

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!" );

このトピックへの返信は締め切られました。

返信数 4

Legend
July 30, 2020

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 ('.')

Stephen Marsh
Community Expert
Community Expert
July 30, 2020

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 }

 

SuperMerlin
Inspiring
July 30, 2020

Another option...

var layerName = decodeURI(app.activeDocument.name).replace(/.\.[^\.]+$/, '');
rob day
Community Expert
Community Expert
July 29, 2020

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);

 

Participating Frequently
July 30, 2020

Thank you!

JJMack
Community Expert
Community Expert
July 29, 2020

Change statement that sets the text layer content to what you want

myTextRef.contents = fileNameNoExtension;

JJMack
Participating Frequently
July 30, 2020

Thank you.