我有一个Google文档,其文本下面带有一条水平线。如果用户从ui.alert
中选择“否”,则需要删除所有这些文本(使用正则表达式简单)和水平线。我不知道如何通过Google Apps脚本删除此水平线。在文档中找不到关于它的任何内容。有人有想法么?谢谢!
var regExpFirstBriefing = "[A-Z \(\)]{42}\\v+[A-Za-z\.\", ]*[\\v+]{1}"; // This accounts for all the text I need removed along with an extra new line. The horizontal line is the next line.
// Ask user if this is the first briefing
var responseFirstBriefing = ui.alert('Question here...' , ui.ButtonSet.YES_NO);
if (responseFirstBriefing == ui.Button.YES) {
document.replaceText(regExpFirstBriefing, '');
}
答案 0 :(得分:1)
ui.alert
中选择“否”时,您想在上面运行。如果我的理解是正确的,那么该示例脚本如何?尽管我不确定您的实际文档,但是根据您的解释,我为它成像并准备了一个示例脚本。请认为这只是几个答案之一。该示例脚本的流程如下。
findText()
搜索搜索文本。offsetValue
将搜索“ HORIZONTAL_RULE”。在此示例中,将在前面最多搜索3段。当上述流程反映到脚本时,它如下所示。
运行脚本时,用regExpFirstBriefing
搜索的文本将被清除,并且该文本下方的“ HORIZONTAL_RULE”也将被删除。
function myFunction() {
var document = DocumentApp.getActiveDocument(); // Added
var ui = DocumentApp.getUi(); // Added
var regExpFirstBriefing = "[A-Z \(\)]{42}\\v+[A-Za-z\.\", ]*[\\v+]{1}";
var responseFirstBriefing = ui.alert('Question here...' , ui.ButtonSet.YES_NO);
if (responseFirstBriefing == ui.Button.YES) {
document.replaceText(regExpFirstBriefing, '');
// I added below script.
} else if (responseFirstBriefing == ui.Button.NO) {
var offsetValue = 3; // When "HORIZONTAL_RULE" doesn't adjacent the searched text, "HORIZONTAL_RULE" is searched by "offsetValue". In this sample, it is searched up to 3 paragraph ahead.
var body = document.getBody();
var r = body.findText(regExpFirstBriefing);
var remove = [];
while (r) {
remove.push(r.getElement().asText())
var parentParagraph = body.getChildIndex(r.getElement().getParent());
var totalChildren = body.getNumChildren();
for (var offset = 1; offset <= offsetValue; offset++) {
if (parentParagraph + offset <= totalChildren) {
var nextParagraph = body.getChild(parentParagraph + offset);
if (nextParagraph.getType() === DocumentApp.ElementType.PARAGRAPH) {
var c = nextParagraph.asParagraph().getNumChildren();
for (var i = 0; i < c; i++) {
var childOfNextParagraph = nextParagraph.asParagraph().getChild(i);
if (childOfNextParagraph.getType() === DocumentApp.ElementType.HORIZONTAL_RULE) {
remove.push(childOfNextParagraph.asHorizontalRule());
break;
}
}
if (remove[remove.length - 1].getType === DocumentApp.ElementType.HORIZONTAL_RULE) {
break;
}
}
}
}
r = body.findText(regExpFirstBriefing, r);
}
for (var i = remove.length - 1; i >=0; i--) {
/////
// If you want to delete the paragraph of searched text, please delete this if statement.
if (remove[i].getType() === DocumentApp.ElementType.TEXT) {
remove[i].removeFromParent();
continue;
}
/////
remove[i].getParent().asParagraph().removeFromParent();
}
}
}
[A-Z \(\)]{42}\\v+[A-Za-z\.\", ]*[\\v+]{1}
的正则表达式适用于您的文档。 如果要删除搜索文本的段落,请从上面的脚本中删除以下if语句。
if (remove[i].getType() === DocumentApp.ElementType.TEXT) {
remove[i].removeFromParent();
continue;
}
如果我误解了您的问题,而这不是您想要的结果,我深表歉意。那时,为了正确了解您的情况,您可以提供要使用的示例文档吗?当然,请删除您的个人信息。我想从中确认问题。