Home > Enterprise >  javascript- replace text with part of the file name
javascript- replace text with part of the file name

Time:01-24

I'm trying to create a script in adobe illustrator that will check if a file name contains "ph" 5 numbers. If it has been found then it will replace a part of a text with the match from the file name.

This is what I have so far I just can't get it to work, the text is replaced with "null"

var doc = app.activeDocument;

var name = doc.name;
var match = name.match(/ph\d{5}/);

for (i = 0; i < doc.textFrames.length; i  )
{
    doc.textFrames[i].contents = doc.textFrames[i].contents.replace(/ph00000/gi, match);
}

CodePudding user response:

You can encapsulate the text that you want to replace with group constructs, and since you're using regex replace table

Read more about it here

Example:

const textString = "This is ph54321 or ph12345";

const newString1 = textString.replace(/(ph)\d{5}/gi, function (matches, p1) {
    return p1   "appended"; // "This is phappended or phappended"
});

const newString2 = textString.replace(/ph(\d{5})/gi, function (matches, p1) {
    return "BIGPH"   p1; // "This is BIGPH54321 or BIGPH12345"
});

console.log({newString1});
console.log({newString2});

CodePudding user response:

I'd try this:

var doc = app.activeDocument;

var match = doc.name.match(/ph\d{5}/);

if (match != null) {
  for (i = 0; i < doc.textFrames.length; i  ) {
    doc.textFrames[i].contents = doc.textFrames[i].contents.replace(/ph00000/gi, match[0]);
  }
}
  •  Tags:  
  • Related