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:
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.
CodePudding user response:
Here is an example of how to find the paragraph with the Heading style Title. In my Doc I have a line of text "This is some text" with style Title.
function findTitle() {
try {
let doc = DocumentApp.getActiveDocument();
let body = doc.getBody();
let paras = body.getParagraphs();
let text = null;
paras.some( para => {
let attribs = para.getAttributes();
if( attribs["HEADING"] === DocumentApp.ParagraphHeading.TITLE ) {
text = para.getText();
return true;
}
return false;
}
);
console.log(text);
}
catch(err) {
console.log(err);
}
}
Execution log
8:08:39 AM Notice Execution started
8:08:39 AM Info This is some text
8:08:39 AM Notice Execution completed
CodePudding user response:
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!