Home > Software design >  Count the number of CHARACTERS in a doc
Count the number of CHARACTERS in a doc

Time:11-07

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.

CodePudding user response:

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;
}

CodePudding user response:

There are little to no different when working with DocumentApp and SpreadsheetApp, all you need to do is get the text as string, than use .length to get the char length.

Google Apps Script basically named their function very straightforward, you can either read the documentation, or in many cases just console.log an object to check what methods can be applied.

In this case, a simple .getText() method seems good enough.

function countChar() {
  const body = DocumentApp.getActiveDocument().getBody();
  const text = body.editAsText();
  const charCount = text.getText().length;
  return charCount;
}

But keep in mind that every space or line break also count as char.

  • Related