2017-02-13 136 views
0

我们怎样才能从谷歌文档中删除真的空段落? 此代码将删除包含图像的任何段落,人力资源的等无法了解如何检查,如果一个段落确实是空的? getText()editAsText()什么都不给予了这一点。谷歌文档应用脚本 - 如何删除真的空段落

var doc = DocumentApp.getActiveDocument(); 
var body = doc.getBody(); 
var docParagraphs = doc.getBody().getParagraphs(); 

for (var i = 0; i < docParagraphs.length; i++) { 
    if (docParagraph[i].getText() === '') { 
     docParagraphs[i].removeFromParent(); 
    } 
} 

我知道有相关的话题〜类似的问题,但不一样。 How to find and remove blank paragraphs in a Google Document with Google Apps Script?

UPD:正确答案:

var doc = DocumentApp.getActiveDocument(); 
var body = doc.getBody(); 

for (var i = 0; i < doc.getBody().getParagraphs().length; i++) { 
    if (docParagraph[i].getText() === '') { 
    if (docParagraph_i.getNumChildren() == 0 && i < (docParagraphs.length - 1)) { 
     docParagraph[i].removeFromParent(); 
    } 
    } 
} 

我已经改变了表达过通过电流元件,以限制我算,而不是存储在变量。因为元素被删除(或者在其他实现中被添加,例如),当没有段落但循环会想要得到它们时会出错。

&& i < (...) 

因为最后一段无法删除并引发错误。

回答

0

你会想在之前的段落

paragraph.getNumChildren() //returns the number of children

+0

我试过.getNumChildren()来检查的孩子,我想.getChild()。以前,没有运气几次的getType(),但你的回答告诉我再重新检查。我做了一个暂停,询问的问题后,现在有清醒的头脑中,我用.getNumChildren()不段,但为它的第一个可能的子女(由.getChild())和没的理解,为什么它甚至在抛出一个错误。 getChild()。第一个这样的段落真的是空白的... Thanx! – Bowman

相关问题