I am writing a docs script to print something when certain characters appear in the document.
The problem is that I can't read bulleted-list special characters (check-marks for example)
I can read copied check-marks from a web page or a check mark that was added by script ( using append ) but it will not read a check mark added from the bulleted list.
Is there any way to read bulleted-list items?
function myFunction() {
var body = DocumentApp.getActiveDocument().getBody();
var text = [] ;
text = DocumentApp.getActiveDocument().getBody().getParagraphs();
for (var i = 0; i < text.length; i++)
{
if ( text[i].findText(String.fromCharCode(0x2713)) != null)
{
body.appendParagraph("Para");
}
}}
Related
I am wondering how to copy a google doc, but include the style, links and font, from within google scripts.
I have tried to use the getBody()
DocumentApp.getActiveDocument().getBody().clear()
document2 = DocumentApp.openById("Document_ID").getBody().getText()
DocumentApp.getActiveDocument().getBody().appendParagraph(document2)
But that only copies that raw text.
EDIT:
Removed documents because the question was solved
Your problem is that getText will only return the raw text, nothing more. Treat them as objects instead, iterate, then append one by one.
function appendContents() {
var source = DocumentApp.getActiveDocument().getBody();
var destination = DocumentApp.openById("DOC ID");
var numElements = source.getNumChildren();
for (var i = 0; i < numElements; ++i ) {
var body = destination.getBody()
var element = source.getChild(i).copy();
var type = element.getType();
if( type == DocumentApp.ElementType.PARAGRAPH ){
body.appendParagraph(element);
}
// Add other element types if you are expecting other elements
// e.g. LIST_ITEM, TEXT, TABLE
// Note that different append will be used for each element type.
}
destination.saveAndClose();
}
If you want to add other element types, see list of available ElementTypes
I'm having trouble, replacing text in a Google Doc, using App Script.
Inside the document I have certain tags/tokens like ${TOKEN.SUBTOKEN}. I get the document as text and extract all the TOKEN's as a list with a Regex without issue, but when I want to use the replaceText function, I have issues. When I execute the replaceText line, it doesn't change the value in the document, but returns an element from the document. I can't find a way to replace the text I'm targeting.
var doc = DocumentApp.openById(docId);
var docBody = doc.getBody();
// tokenValues is the Object that contains the values to replace.
var fields = docBody.getText().match(/\$\{[a-z0-9\.\_]+\}/gi);
for (var i = 0; i < fields.length; i++ ) {
fields[i] = fields[i].substring(2, fields[i].length-1);
}
for (var i; i < fields.length; i++) {
Logger.log(docBody.replaceText(new RegExp('\\${ *' + fields[i].replace('/\./g', '\.') + '\ *}', tokenValues[i]));
}
How should I approach this, I'm having trouble with It because the documentation is not that explicit, (or maybe I don't understand it)
I did something similar to your question.
Here's the text:
{{ClientName}} would like to have a {{Product}} {{done/created}}. The purpose of this {{Product}} is to {{ProductPurpose}}. We have experience with such testing and development, and will develop and test the {{Product}} for {{ClientName}}.
Here's the code:
function searchReplace(){
var regex1=new RegExp('{{([a-zA-Z/]+)}}','g');
var tA=[];
var srchA=[];
var fldA=[];
var s=DocumentApp.getActiveDocument().getBody().getText();
while((tA=regex1.exec(s))!==null){//get all fields
fldA.push(tA[1]);
}
for(var i=0;i<fldA.length;i++){//Get unique fields
if(srchA.indexOf(fldA[i])==-1){
srchA.push(fldA[i]);
}
}
var doc=DocumentApp.getActiveDocument();
var body=doc.getBody();
for(var i=0;i<srchA.length;i++){
var searchPattern=Utilities.formatString('\\{\\{(%s)\\}\\}', srchA[i]);//need double backslashes here.
var prompt=Utilities.formatString('Enter Replacement for %s',srchA[i]);
var resp=DocumentApp.getUi().prompt('Replacement Text',prompt , DocumentApp.getUi().ButtonSet.OK_CANCEL)
if(resp.getSelectedButton()==DocumentApp.getUi().Button.OK){
body.replaceText(searchPattern, resp.getResponseText());//replaces all instances of the field
}
}
}
I'm currently using the following Google script to add line breaks in questions:
function addLineBreaks() {
var form = FormApp.getActiveForm();
var multiplechoices = form.getItems(FormApp.ItemType.MULTIPLE_CHOICE);
var date = form.getItems(FormApp.ItemType.DATE);
var textbox = form.getItems(FormApp.ItemType.TEXT);
var checkboxgrid = form.getItems(FormApp.ItemType.GRID)
questions = multiplechoices.concat(date, textbox, checkboxgrid);
for(i = 0; i < questions.length; i++) {
var title = questions[i].getTitle();
if(title.indexOf("\n") < 0) {
questions[i].setTitle(title.replace(" | ", "\n"));
}
}
}
My problem is that I cannot add line breaks to grid rows and general titles (Tt). I'm confident that it's because the script I'm using refers to getTitle, but couldn't get it to work with getRows or setRows.
I don't mind having to add "|" and have it replaced later with a line break when the script runs, but I do need to find a solution regarding the grids (multiple choice grids rows only).
How we can remove really empty paragraphs from Google Document?
This code will remove any paragraphs that contains images, hr's etc. Can't understand how to check if a paragraph really empty?
getText() and editAsText() gives nothing to this.
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var docParagraphs = doc.getBody().getParagraphs();
for (var i = 0; i < docParagraphs.length; i++) {
if (docParagraph[i].getText() === '') {
docParagraphs[i].removeFromParent();
}
}
I know there are topic related to ~similar problem, but not the same. How to find and remove blank paragraphs in a Google Document with Google Apps Script?
UPD: correct answer:
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
for (var i = 0; i < doc.getBody().getParagraphs().length; i++) {
if (docParagraph[i].getText() === '') {
if (docParagraph_i.getNumChildren() == 0 && i < (docParagraphs.length - 1)) {
docParagraph[i].removeFromParent();
}
}
}
I've changed for expression too to limit i by a current elements count, not stored in variable. Because elements are deleted (or in other implementation added, for example) there will be error when no paragraphs but cycle will want to get them.
&& i < (...)
because last paragraph can't be deleted and throws an error.
You will want to check for children in the paragraph
paragraph.getNumChildren() //returns the number of children
Trying to work out how to remove multiple line breaks from Google Documents (not spreadsheets).
I've tried this and many variations thereof:
function searchAndReplace() {
var bodyElement = DocumentApp.getActiveDocument().getBody();
bodyElement.replaceText("\r\r", '\r');
}
Any idea please?
Noob to all of this...
Purpose is to replicate the search and replace in MS Word for ^p
Here is a rather "radical" method if your document has only paragraphs with text (images or other elements will be lost). See doc about element types here
(comments in code)
function removeNewLines(){
var doc = DocumentApp.getActiveDocument();
var text = doc.getBody().getText();// get a string
var textMod=text.replace(/\n/g,'');// replace all \n with ''
Logger.log(textMod);//optional check in logger
doc.getBody().clear().appendParagraph(textMod);// empty the doc and apend new texr
doc.saveAndClose();// save the result
}
I wanted to do the same thing (replace two new lines with a single new line). Ended up with the following as replaceText() doesn't accept \n for some reason.
function myFunction() {
var body = DocumentApp.getActiveDocument().getBody();
var text = body.editAsText();
var text_content = text.getText();
for(var i = 0, offset_i = 0; i < (text_content.length); i++){
if((text_content.charCodeAt(i)==10) && (text_content.charCodeAt(i-1)==10)){
text.deleteText(i-1-offset_i, i-1-offset_i)
offset_i++;
}
}
}
This code helped me to remove doubled new lines in document:
function removeDoubleNewLines(){
var doc = DocumentApp.getActiveDocument();
var paragraphs = doc.getBody().getParagraphs();
var paragraph;
for (var i = 0; i < paragraphs.length-1; i++) {
paragraph = paragraphs[i];
if(paragraph.getText() === '' &&
paragraph.getNumChildren() === 0) {
paragraph.removeFromParent();
}
}
}