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

Indesign Javascript - Make an array from grep query

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

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

Indesign text example

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

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

谢谢

在这里发现类似问题后: 我以该代码为起点并对其进行了修改。

我遇到的第一个问题是我不知道如何访问查找功能的内容。 Find 中的 InDesign returns 实际上是一个文本对象数组 (http://jongware.mit.edu/idcs6js/pc_Array.html)。

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

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

如上所述,数组的内容是文本对象的集合,Indesign 将通过访问数组的第一个条目来 return。 接下来,我必须将文本对象转换为字符串,这样我才能访问找到的文本的实际内容。我从这里 post 那里得到了一个消息 How to store value to variable in InDesign GREP find / change using javascript

var firstResult = found_txt.contents;

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

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[=12=]";
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;
}