google-apps-scriptgoogle-docsfootnotes

Can Google App Scripts access the location of footnote superscripts programmatically?


Is it possible to use DocumentApp to find the location of footnote references in the body?

Searching the body or an element using editAsText() or findText() does not show the superscript footnote markers.

For example, in the following document:

This is a riveting story with statistics!1 You can see other stuff here too.

body.getText() returns 'This is a riveting story with statistics! You can see other stuff here too.' No reference, no 1

If I want to replace, edit, or manipulate text around the footnote reference (e.g. 1 ), how can I find its location?


Solution

  • It turns out that the footnote reference is indexed as a child in the Doc. So you can get the index of the footnote reference, insert some text at that index, and then remove the footnote from its parent.

    function performConversion (docu) {
    
      var footnotes = docu.getFootnotes() // get the footnote
    
      var noteText = footnotes.map(function (note) {
        return '((' + note.getFootnoteContents() + ' ))' // reformat text with parens and save in array
      })
    
      footnotes.forEach(function (note, index) {
        var paragraph = note.getParent() // get the paragraph
    
        var noteIndex = paragraph.getChildIndex(note) // get the footnote's "child index"
    
        paragraph.insertText(noteIndex, noteText[index]) // insert formatted text before footnote child index in paragraph
    
        note.removeFromParent() // delete the original footnote
      })
    }