gpt4 book ai didi

javascript - 删除一段文字

转载 作者:行者123 更新时间:2023-11-29 10:40:16 25 4
gpt4 key购买 nike

我构建了一个应用脚本来复制文档并根据我输入到 Google 电子表格中的数据对其进行编辑。

一旦文档被复制和编辑,我想删除某些文本段落。

我正在使用以下内容来查看是否可以找到我正在搜索的文本,但我的代码返回了 Range Element.

var body = DocumentApp.openById(copyID).getBody();
var para = body.findText('X1');

Logger.log(para);

我的理想状态是为应用程序脚本提供文档中的两个位置,然后让应用程序脚本删除该范围内的所有文本。

如何生成正确的偏移量并删除文本?

最佳答案

I was using the following to see if I could find the position of the text I was searching for, but my code returned Range Element.

这应该会发生,这里是文档中有关范围元素的一些信息。

Class RangeElement
A wrapper around an Element with a possible start and end offset. These offsets allow a range of characters within a Text element to be represented in search results, document selections, and named ranges.
https://developers.google.com/apps-script/reference/document/range-element


My ideal state would be to provide apps script with two positions within the document, and then have Apps Script delete all the text within those ranges.

使用以下命令检索偏移量并删除文本。

var startOffset = rangeElement.getStartOffset();
var endOffset = rangeElement.getEndOffsetInclusive();
rangeElement.getElement().asText().deleteText(startOffset,endOffset);

getStartOffset()
Gets the position of the start of a partial range within the range element. If the element is a Text element and isPartial() returns true, the offset is the number of characters before the start of the range (that is, the index of the first character in the range); in any other case, this method returns -1.
https://developers.google.com/apps-script/reference/document/range-element#getStartOffset()

getEndOffsetInclusive()
Gets the position of the end of a partial range within the range element. If the element is a Text element and isPartial() returns true, the offset is the number of characters before the last character in the range (that is, the index of the last character in the range); in any other case, this method returns -1.
https://developers.google.com/apps-script/reference/document/range-element#getEndOffsetInclusive()

deleteText(startOffset, endOffsetInclusive)
Deletes a range of text.
https://developers.google.com/apps-script/reference/document/text#deleteText(Integer,Integer)


How can I generate the correct offsets and delete the text?

下面的脚本会做到这一点。

var rangeElement = DocumentApp.openById(copyID).getBody().findText('X1');
if (rangeElement.isPartial()) {
var startOffset = rangeElement.getStartOffset();
var endOffset = rangeElement.getEndOffsetInclusive();
rangeElement.getElement().asText().deleteText(startOffset,endOffset);
} else {
rangeElement.getElement().removeFromParent();
}

关于javascript - 删除一段文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30578496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com