Wednesday, 26 March 2025

Google Docs and Sheets AppScript to add menu and replace new lines

 


function onOpen() {
  const ui = DocumentApp.getUi();
  const menu = ui.createMenu('AK Menu'); // Replace 'My Menu' with your desired menu name
  menu.addItem('AKReplace', 'replaceAKNewlinesAndCaptureExpressions'); // Replace 'Show Spreadsheet Name' and 'showName' with your desired item name and function name
  menu.addToUi();
}


function replaceAKNewlinesAndCaptureExpressions() {
  // allows google docs to use matching capture in replace expression
  // eg (\d\d )\n - find things like 10 \n - newline
  // replace with $1  - removes the new line character and keeps the digits eg 11
  var body = DocumentApp.getActiveDocument().getBody();
  var paragraphs = body.getParagraphs();
   const ui = DocumentApp.getUi();
    const response = ui.prompt(
    'Search Text? (currently HARDCODED)',
    ui.ButtonSet.YES_NO,);

  for (var i=0; i<paragraphs.length; i++) {
    var text = paragraphs[i].getText();

    // need to create an input form here or two or three popups for search text
    // replace text
    paragraphs[i].replaceText("(\d\d) \n", "$1") ;
  }
}

No comments: