使用Script Lab组合两个段落



我是Script Lab的新手。我昨天刚刚发现这个工具,并试图找到和删除一个新的行或段落的结尾,但没有运气到目前为止。在RegEx上下文中,我试图找到wsn,这意味着-一个小写字母,然后是一个空格,然后是一个新行。我试着运行这段代码

async function run() {
await Word.run(async (context) => {
const results = context.document.body.search("wsn", { matchWildcards: true });
results.load("length");
await context.sync();
results.items.forEach((word) => {
// ideally i would end up something like this 'n[space][new line]' and then I want to remove the new line and end up only with 'n[space]'. How can I make this?
});
await context.sync();
});
}

如果有人可以向我展示查找和替换的工作演示这也将帮助我理解这个框架是如何工作的。谢谢。

我想在Word中找到所有具有此正则表达式wsn的段落,但是正则表达式在Word API中不像@Rick提到的正常正则表达式那样工作,所以我最终使用其他方法来捕获我需要的段落。我看到每个段落的firstLineIndent都是-18。所以我做了一个if,修剪段落trimmed = currentPara.text.trim();,这样我就可以去掉后面的空格检查最后一个字符是否不是.!?,然后如果所有这些都是真的,将下一段添加到当前的currentPara.insertText(nextPara.text, "End");,然后简单地删除下一段,因为我不再需要它了-nextPara.delete();

这是我的解

async function run() {
await Word.run(async (context) => {
const paragraphs = context.document.body.paragraphs;
paragraphs.load("items");
await context.sync();
let currentPara;
let nextPara;
let trimmed;
let lastChar;
for (let i = 0; i < paragraphs.items.length; i++) {
currentPara = paragraphs.items[i];
nextPara = paragraphs.items[i+1];
trimmed = currentPara.text.trim();
lastChar = trimmed[trimmed.length - 1];
if (currentPara.firstLineIndent == -18 && lastChar != "." && lastChar != "!" && lastChar != "?") {
currentPara.insertText(nextPara.text, "End");
nextPara.delete();
// here I change the current paragraph style
currentPara.firstLineIndent = 18;
currentPara.isListItem = false;
currentPara.leftIndent = 0;
}
}
});
}

希望这能帮助到别人。从两天的Word API工作来看,我可以说有一些限制,但有了逻辑,你可以达到你的目标。

最新更新