I am simply looking to get a count of the character (not the words) in a Google document. It cannot be in the active document for this use case, so would need to be post getBody
.
Here is my very fragmented script so far. For context, I am looking to integrate a few features into a collaborator's document, at the end of the document. From what I can see so far I would need the character count (+1) to acheive this.
function myFunction() {
var doc = DocumentApp.openById([ID]);
var bodyCount = doc.getBody().getText();
var body = doc.getBody();
//var numChildren = body.getNumChildren();
//var pos = doc.newPosition(body.getChild(numChildren - 1),0);
var text = body.editAsText();
var space = " ";
//var text = DocumentApp.getActiveDocument().getBody().getText();
var words = bodyCount.replace(/\s+/g, space).split(space);
Logger.log(words.length);
const characters = words.join('');
Logger.log(characters);
var charCount = characters.toString();
Logger.log(charCount);
var realCharCount = charCount.length();
//body.setCursor(pos);
text.insertText(words.length,"yadayadayada");
}
Just want to insert text, it needs to be the integer for the position AKA, +1 of the character count. I have most of the functions I need so far except getting that one number: the character count.
This is NOT to count characters in a cell, nor is it related in any way to sheets. That would be nice because than I could just use the length function... but I cannot in this context so far.
Character Count:
function getCharacterCount() {
const ch = "ABCDEFGJHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";//You can add or remove what you wish to call legal characters this way
const doc = DocumentApp.openById();
const body = doc.getBody();
let txt = body.getText();
let s = txt.split('').filter(c => ~ch.indexOf(c)).filter(e => e);
let l = s.length;
Logger.log(l);
return l;
}