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?