微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Indesign Javascript - 从 grep 查询创建一个数组

如何解决Indesign Javascript - 从 grep 查询创建一个数组

我有一个很长的条目列表,我可以通过 GREP 查询选择我需要的单个条目,但我想要做的是,每次 GREP 查询找到匹配项时,我希望它将该选择添加到大批。关键是,如果我将特定搜索中的所有项目都放在一个数组中,我就可以找到我的查询的第一个实例,并在任何返回的条目之前放置一个标题

举例说明我正在努力实现的目标可能会有所帮助。 下面是我拥有的信息列表的示例,您可以在左侧看到文本是如何提供的。 “主题展览”出现在每个条目的开头。我想从每一行的开头删除单词,而是在第一个条目之前放置一个标题

Indesign text example

我需要帮助的是弄清楚我应该如何构建 Javascript 以便我可以弄清楚主题展览条目的第一个实例是什么。

我认为它会涉及一个 for 循环,每次循环时它都会执行 grep find 并将其添加到数组中,但我不确定这是否是解决问题的最佳方法

谢谢

解决方法

在此处发现类似问题后:JavaScript + InDesign: Find a word in a .indd document and write a .txt file with page number locations 我以该代码为起点,重新编写了它。

我遇到的第一个问题是我不知道如何访问 find 函数的内容。 InDesign 从 Find 返回的实际上是一个文本对象数组 (http://jongware.mit.edu/idcs6js/pc_Array.html)。

所以第一步是将 Find 的第一个结果放入一个变量中。

var found_txt = app.activeDocument.findGrep ()[0];

如上所述,数组的内容是文本对象的集合,这就是 Indesign 将通过访问数组的第一个条目返回的所有内容。 接下来,我必须将文本对象转换为字符串,以便我可以访问找到的文本的实际内容。我从这篇文章中得到了一个提示 How to store $2 value to variable in InDesign GREP find / change using javascript

var firstResult = found_txt.contents;

通过应用 .contents 并将其放入一个新变量中,我现在可以访问搜索结果中的文本字符串。 下面是执行我最初发布的问题的任务的完整代码。希望它对其他人有用。

main ();

function main() {
var grepQuery = "Subject Exhibition:.+$";

//Clear any existing Grep preferences
app.findGrepPreferences = NothingEnum.nothing;
app.changeGrepPreferences = NothingEnum.nothing;

// set some options,add any that are needed
app.findChangeGrepOptions.includeLockedLayersForFind = true;
app.findChangeGrepOptions.includeLockedStoriesForFind = true;
app.findChangeGrepOptions.includeHiddenLayers = true;
app.findChangeGrepOptions.includeMasterPages = false;
app.findChangeGrepOptions.includeFootnotes = true;

//Put the search term into the query
app.findGrepPreferences.findWhat = grepQuery;

//Put the first result of the find into a variable
var found_txt = app.activeDocument.findGrep ()[0];
//the find operation will return an Array of Text Objects.
//by using Javascripts CONTENTS it takes the reult and converts it into a regular String rather than a Text Object.
var firstResult = found_txt.contents;

//clear the preferences
app.findGrepPreferences = NothingEnum.nothing;
app.changeGrepPreferences = NothingEnum.nothing;

//For the lookahead to work it needs something in front of it so I have told it to look for the return.
var newQuery = "\\r(?=" + firstResult + ")"
app.findGrepPreferences.findWhat = newQuery;


//and add in the Section Header and Subject Exhibiton header above the found instance
app.changeGrepPreferences.changeTo = "\\rSubject Exhibition\\r$0";
app.changeGrepPreferences.appliedParagraphStyle = "Award Header";

//Run the find\Change
app.activeDocument.changeGrep ();

//Clear Grep preferences
app.findGrepPreferences = NothingEnum.nothing;
app.changeGrepPreferences = NothingEnum.nothing;    

alert("Finished");
return;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。