【问题标题】:javascript- replace text with part of the file namejavascript-用文件名的一部分替换文本
【发布时间】:2022-01-24 00:09:56
【问题描述】:

我正在尝试在 adobe illustrator 中创建一个脚本,该脚本将检查文件名是否包含“ph”+5 数字。 如果已找到,它将用文件名中的匹配项替换部分文本。

这是我目前所拥有的,我无法让它工作,文本被替换为“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);
}

【问题讨论】:

  • 我建议不要在 Illustrator 脚本中使用名称 name。 Illustrator 的 API 有很多错误,并且名称为 name 的变量通常包含“Adobe Illustrator”字符串,而不是您放入其中的任何内容。

标签: javascript adobe-illustrator extendscript


【解决方案1】:

我会试试这个:

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

【讨论】:

    【解决方案2】:

    您可以用组结构封装要替换的文本,并且由于您使用的是String.prototype.replace,因此您可以捕获带括号的组并将回调函数作为.replace 函数中的第二个参数传递。

    阅读更多信息here

    例子:

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

    【讨论】:

    • 唉,Adobe Illustrator 没有箭头功能。如果你为 Extendscript (~ES3) 重写它会很好。
    • @YuriKhristich 已编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2013-12-03
    • 2013-01-07
    • 1970-01-01
    • 2016-11-02
    相关资源
    最近更新 更多