Question

I am trying to write a merg script using goolge documents and referencing a seperate spreadsheet.

I am currently stuck, it doesn't replace any of the content and the forloop stops at i=0.

Here is the code:

function myMerger(body, myArrayOfWords, myArrayOfData){//this function will replace the terms found in myArrayOfWords with 
  Logger.log(' just starter myMerger');
  Logger.log('myArrayOfWords.length is '+myArrayOfWords.length);
  Logger.log('myArrayOfData.length is ' +myArrayOfData.length);
  for(i=0;i<myArrayOfWords.length;++i){//for loop replaces will run the following code for each string within myArrayOfWords
    Logger.log('myMerger forloop instance number '+i);
    Logger.log('replacing '+myArrayOfWords[i]+' with '+myArrayOfData[i]);
    body.replaceText(myArrayOfWords[i], myArrayOfData[i]);
    //replaces the string in the document with a value from myArrayOfData
  }
}

The logger returns the following:

[14-04-24 12:07:40:248 PDT] just starter myMerger
[14-04-24 12:07:40:248 PDT] myAraryOfWords.length is 23
[14-04-24 12:07:40:248 PDT] myArrayOfData.length is 23
[14-04-24 12:07:40:248 PDT] myMerger forloop instance number 0
[14-04-24 12:07:40:248 PDT] replacing **!WeekOf!** with 12

Then it stops. I can't tell if I just built a bad for loop or if there is an error that I am not aware of. I am not sure how to check for what is breaking it.

Was it helpful?

Solution

The problem is that replaceText always understands the string to be replaced as a regular expression pattern and * have a special meaning in a regexes. You should use # or any other char that does not have a special meaning as your "separator".

Anyway, it's a "good practice" to escape everything if you're not expecting a regexp. Like this:

function escapeRegex(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }

function myMerger(body, myArrayOfWords, myArrayOfData){//this function will replace the terms found in myArrayOfWords with 
  Logger.log(' just starter myMerger');
  Logger.log('myArrayOfWords.length is '+myArrayOfWords.length);
  Logger.log('myArrayOfData.length is ' +myArrayOfData.length);
  for(i=0;i<myArrayOfWords.length;++i){//for loop replaces will run the following code for each string within myArrayOfWords
    Logger.log('myMerger forloop instance number '+i);
    Logger.log('replacing '+myArrayOfWords[i]+' with '+myArrayOfData[i]);
    body.replaceText(escapeRegex(myArrayOfWords[i]), myArrayOfData[i]);
    //replaces the string in the document with a value from myArrayOfData
  }
}

I got this neat code from Bobince's answer.

By the way, you should have pasted the error message you got when you ran this code. It would've helped me to answer you faster: Invalid regular expression pattern **!WeekOf!**

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top