Search code examples
google-apps-scriptreturn-valuegoogle-docs

Copy Document Title Using Google App Script


I want to copy the text from the title within this document, but I am only used to using Google App Script in sheets, not docs: Where the text is in the document

I have tried lot of different methods, but nothing is populating in Logger.log(), so I am not sure it is working. Currently, all I want to return is the text in the Title, so I can go on to search for this in a spreadsheet. So far I have the following:

function autoFill() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var searchResult = body.findElement(DocumentApp.ElementType.PARAGRAPH);
  var searchHeading = searchResult.getElement(DocumentApp.ParagraphHeading.TITLE);

The only part of the document that has the format of Title is the first line in the document.


Solution

  • Found that using Regular Expression would be able to identify the text needed:

     function autoFill() {
      var ss = DocumentApp.getActiveDocument();
      var body = ss.getBody();
      var header = DocumentApp.getActiveDocument().getHeader();
      var contents = body.getText();
      var racm = SpreadsheetApp.openById('[enter sheet ID').getSheetByName('Risks & Controls matrix');
      var lr = racm.getLastRow();
      var colID = racm.getRange(1,1,lr,1).getValues();
    
    //you need to tweak below to the control name pattern
    
      var regexName = /\w+[-]\w+[-]\w+/   //use website: regexr.com to create & www.geeksforgeeks.org/write-regular-expressions/
      var titleFound=regexName.exec(contents)[0];
    
    let row = colID.findIndex(users => {return users[0] == titleFound})+1; 
    

    Then goes on to finding the relevant data in the ranges from the spreadsheet and .replaceText() within the doc.

    Works really well. Thanks for your help!