0

I am using a modified version taken from this useful answer to get numbers in my Google Docs Header 2:

function myFunction() {
  var pars = DocumentApp.getActiveDocument().getParagraphs();
  var counterh2 = 0;
  for (var i in pars) {
    var par = pars[i];
    var hdg = par.getHeading();
    if (hdg == DocumentApp.ParagraphHeading.HEADING2) {
      counterh2++;
      var content = par.getText();
      var chunks = content.split('\t');
      if (chunks.length > 1) {
        par.setText(content.replace(/$[0-9\s]+/, '')); // Not working
        par.setText(chunks[1] + ' ' + counterh2);
      } else {
        par.setText(content.replace(/$[0-9\s]+/, '')); // Not working
        par.setText(chunks[0] + ' ' + counterh2);
      }
    }
  }
}

However, when pressing Run several times, it keeps adding numbers to the Header e.g:

This is the Header 1 1 1

(Pressed Run button 3 times).

I need to edit the Headers several times because I need to add or delete them while I'm writing. It is a dynamic document and not edited only by me.

So how can we prevent adding numbers in Headers in Google Docs?

2

1 Answer 1

1

The regex /$[0-9\s]+/ attempts to match numbers and whitespace immediately after the end of line. That will never match anything. Use /[\s\d]+$/ to match numbers and whitespace immediately before the end of line.

You apparently to want to add numbering to the end of headings. The split() and if seem unnecessary and can probably be removed. Simply use this:

par.setText(content.replace(/[\s\d]*$/, ' ' + counterh2));

That will replace numbers and whitespace with a space and counter at the end of line, or add a space and counter when they are missing.

2
  • It worked pretty well, thank you!! Another point I would like to achieve is not to giving permission to run the code because every collaborator of the Doc must go accept the permission, right? Is there an easy way to share this code to the collaborators without asking them for permission?
    – manooooh
    Jan 16, 2022 at 21:37
  • It would probably be much easier to just use the Google Docs built-in heading numbering feature. Please ask only one question per post. Jan 17, 2022 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.