Issue with body.replaceText() in Google Docs - google-apps-script

I am populating a Google Doc template based on a Google Form submission. Upon submit, the program copies the template Google Doc, captures the first item from the Google Form which is always the person's name (because this is a required field), and then replaces {{Name}} in the new file with the entered name using:
var name = itemResponses[0].getResponse();
body.replaceText('{{Name}}', name);
That works correctly. But then I iterate through the rest of the item response and not all the items are required, so I use a lookup table in a Google sheet. The loop takes the item id in the item response and then looks up the text that the response will replace. Then the program does:
var textToReplace //this value is from column B in the Google Sheet lookup table
var newText //this value is the entered response from the Google Form
body.replaceText(textToReplace, newText);
When I do this, I am getting a "Exception: Invalid argument: searchPattern" error. Why are these two body.replaceText() functions different? They are both finding a variable with in double brackets in the Google doc, but it only works in one case.
And to be clear, this was previously working correctly for the last couple of months and only recently started to not work (maybe Google changed something??). My hypothesis is that it has to do with a regex pattern in the first parameter of replaceText.

The "searchPattern" error is a good clue, in certain circumstances, it tells us the value of "textTopReplace" is not a valid search pattern. Since the code hasn't changed, the lookup table in your spreadsheet, or the fields on the form probably have.
One of your lookups is returning a value that isn't a valid search pattern. Perhaps it is returning Null, or an empty string?
You can get more information by using console.log to log debug info to the stackdriver log interface provided by Google, like so:
console.log('text to replace: "'+textToReplace+'"'); //this value is from column B in the Google Sheet lookup table
console.log('value: "'+newText+'"'); //this value is the entered response from the Google Form
body.replaceText(textToReplace, newText);
Then, to view the logs, select "stackdriver logging" from the View menu.

Related

How to append data to next column, using Google Sheets API?

I need to append data to a new column of a spreadsheet, every day.
But I want to make it automatically, just like spreadsheets.values.append does: but for columns.
spreadsheets.values.append will only append data to new rows, not columns!
I have tried these params:
majorDimension does work for me:
Invalid JSON payload received. Unknown name "majorDimension": Cannot bind query parameter. Field 'majorDimension' could not be found in request message.
InsertDataOption doesn't seem to make any difference
I'm sending data to a named range called "foo". When foo is already filled, the API places data at the bottom. I need the data to be place to the right.
You could push each element of the new column into each row of the 2d array with something like this: https://stackoverflow.com/a/68886835/7215091 In that case I used splice but you could probably use push instead.

Extract href attribute from HTML text in Google Sheets

I have about 3000 rows in my Google Spreadsheet and each row contains data about one article from our website. In one column (e.g. A:A) is stored formated text in HTML. I need extract all URLs inside href="" attribute from this column and work with them later. (It could be array or text string separated with coma or space in B column)
I tryied to use REGEXTRACT formula but it gives me only the first result. Then I tryied to use REGEXREPLACE but I'm unable to write proper expression to get only URL links.
I know that it is not proper way to use regex to get anything from HTML. Is there another way to extract these values from HTML text in one cell?
Link to sample data: Google Spreadsheet
Thak you in advance! I'm real newbie here and in scripting, parsing etc. too.
How about this samples? I used href=\"(.*?)\" for retrieving the URL. The sample of regex101.com is here.
1. Using Google spreadsheets functions :
=TEXTJOIN(CHAR(10),TRUE,ARRAYFORMULA(IFERROR(REGEXEXTRACT(SPLIT(a1,">"),"href="&CHAR(34)&"(.*?)"&CHAR(34)))))
In this case, since REGEXEXTRACT retrieves only the first matched string, after the cell data is separated by SPLIT, the URL is retrieved by REGEXEXTRACT.
Result :
2. Using Google Apps Script :
function myFunction(str){
var re = /href=\"(.*?)\"/g;
var result = "";
while ((res=re.exec(str)) !== null) {
result += res[1] + "\n";
};
return result.slice(0,-1);
}
This script can be used as a custom function. When you use this, please put =myFunction(A1) to a cell.
Result :
The result is the same to above method.
If I misunderstand your question, I'm sorry.

Retrieve Google Spreadsheet Worksheet JSON

I try to receive the JSON of a Google Spreadsheet Worksheet. It worked till some days ago. For the default worksheet it still works, but not for all other worksheets.
This is the working URL for the default worksheet: https://spreadsheets.google.com/feeds/list/1caRqAA1TyBoZ0eVZvvKheEBh9SGRmQII4qih9urY70k/od6/public/full?alt=json
And this is the URL for the worksheet that stopped working: https://spreadsheets.google.com/feeds/list/1caRqAA1TyBoZ0eVZvvKheEBh9SGRmQII4qih9urY70k/1416241220/public/full?alt=json
The error message is Invalid query parameter value for grid_id.
Only difference is the worksheet parameter (od6 vs 1416241220).
Any ideas on why that error suddenly occurs?
ChrisPeterson's note:
You can use worksheet position number (1 for the first/default worksheet, 2 for the second worksheet).
Original answer
I came across the same issue and I managed to find my way out.
It seems that they recently changed the id for each worksheet.
You can find the new ID at the following
https://spreadsheets.google.com/feeds/worksheets/YOUR_SPREADSHEET_ID/private/full
I got something like o3laxt8 between <id> tags
Ps: od6 anddefault values will always work and redirect to the first worksheet of your document.
Joe Germuska' note:
od6 doesn't work anymore
Seems to work again.
I'd like to share a concrete example because I find there are enough confusing instructions out there including the accepted answer and worksheet IDs and where to put them not being obvious.
Here's a document I published and anyone with the link can view:
https://docs.google.com/spreadsheets/d/1QDWpycJJFA-UAiSPIv-icJ4UZhbEmuN8wxxag83SE1c/edit?usp=sharing
The document has to be published correctly. There are two Publish buttons and the first one doesn't work for this task. Use the second.
The document KEY is important. Obtain the KEY from between the /d/ and the /edit in the url. In my example, the key is 1QDWpycJJFA-UAiSPIv-icJ4UZhbEmuN8wxxag83SE1c.
Second, use the following URL style, replacing KEY with your own:
https://spreadsheets.google.com/feeds/list/KEY/od6/public/values?alt=json
My example url links directly to published json:
https://spreadsheets.google.com/feeds/list/1QDWpycJJFA-UAiSPIv-icJ4UZhbEmuN8wxxag83SE1c/od6/public/values?alt=json
Finally, if the worksheet has multiple sheets (or tabs), replace od6 in the url with a number. My example has two tabs, so there are two urls corresponding to either tab. I simply replace od6 with 1 and 2 depending on the order of the sheets:
Tab 1:
https://spreadsheets.google.com/feeds/list/1QDWpycJJFA-UAiSPIv-icJ4UZhbEmuN8wxxag83SE1c/1/public/values?alt=json
Tab 2:
https://spreadsheets.google.com/feeds/list/1QDWpycJJFA-UAiSPIv-icJ4UZhbEmuN8wxxag83SE1c/2/public/values?alt=json
In the event of a worksheet where the tabs are reordered frequently, it is possible to get the ID of a given sheet and use that instead of ordered numbers. I first learned of this approach from this post or this post:
In brief, you would reform a private URL with your KEY:
https://spreadsheets.google.com/feeds/worksheets/KEY/private/full
This only works on a browser where you are logged into Google Drive on an account with permissions.
Next, you have to sift through XML to find your sheet IDs:
Replace the previous 1 and 2 with the IDs, for example:
Tab 1 (first worksheet id in a new google sheet is always od6 by default, no matter order of tabs):
https://spreadsheets.google.com/feeds/list/1QDWpycJJFA-UAiSPIv-icJ4UZhbEmuN8wxxag83SE1c/od6/public/values?alt=json
Tab 2:
https://spreadsheets.google.com/feeds/list/1QDWpycJJFA-UAiSPIv-icJ4UZhbEmuN8wxxag83SE1c/ope57yg/public/values?alt=json
You can find the new ID at the following
https://spreadsheets.google.com/feeds/worksheets/YOUR_SPREADSHEET_ID/private/full

How query/search for information from one Google spreadsheet to another spreadsheet using GAS?

I would like to create a Google Apps Script to do the following: When I select a cell containing the name of a person in a spreadsheet (a spreadsheet that records sales, for example), and use a menu button to call the function, the script does a search (a query) using the person's name (or number of his document) in another spreadsheet that stores complete consumer data and that contains all the information that I need from that consumer to generate a contract or a payment receipt.
What is the best strategy to implement this search for information from one spreadsheet in another spreadsheet using Google Apps Script?
Do you have some script sample with a implementation similar to this? THANK YOU in advance for any help/guidance!
There is no event triggered by a cell selection, you'll have to use a menu item or a button to call the function or, if it is acceptable for your use case, edit the cell to trigger an onEdit event.
The 'search part' is actually very simple, the data being on the spreadsheet itself or in another one has no importance, it will simply change the way you access data ( getActiveSpreadsheet or openById()). From there just get all the values and do a search in the resulting 2D array.
EDIT following your comment : here is an example of such a code that returns the range of the found cell (and we get the A1 notation but we could getValue() as well of course.).
function test(){ // to test the find function with an argument, 'any' in this case
var result = findItem('any');
if(result){Logger.log(result.getA1Notation())}else{Logger.log('no luck !')};
}
function findItem(item){
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = ss.getDataRange().getValues()
for(var n = 0;n<data.length;++n){
if(data[n].indexOf(item)>-1){ // this is a "strict" find, ie the value must be the entire search item. If you want to do partial match you should compare differently...
return (ss.getRange(n+1,data[n].indexOf(item)+1)); // if found return the range. note the +1 because sheets have 1 index while arrays have 0 index
}
}
return false;// if we come to the end of sheet without result...
}

Google Apps Script in Spreadsheet storing decimal values instead of Integer in Project Properties

This is my first post. I tried searching via Google and this site but really couldn't find any info about typecasting or converting numerical values within GAS specifically in this scenario. So here the problem:
I have a very basic script attached to a Google Spreadsheet. The script simply keeps track of the last row that was populated, increments the value by one, so that the next row can be populated. I'm storing the "last row used" as a Project Property. For some reason, the script keeps writing the value back into Project Properties as a decimal value, which throws off the whole script since it seems I can't use a decimal value to reference a cell location.
Here is the code snippet:
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var value = ss.getSheetByName("Sheet1").getRange("D13").getValue().toString();
var last = ScriptProperties.getProperty("last");
var therowx = parseInt(ScriptProperties.getProperty("therow"));
Browser.msgBox("The last row is: " + therowx);
if( value != last ) {
ScriptProperties.setProperty("last", value);
ScriptProperties.setProperty("therow", therowx + 1);
}
}
Assuming that I've pre-set the Property to 1 before running the script, once this method fires, it sets it to 2.0 instead of just 2. I've tried wrapping the method call with the Number() and parseInt() functions but they don't seem to make a difference.
I'm open to suggestions, as I'm sure I'm doing something wrong but just not quite sure what.
It would appear that you are using a value from the spreadsheet with var value = ss.getSheetByName("Sheet1").getRange("D13").getValue().toString();
This is were you are getting the decimal as Google spreadsheets will default to one decimal place. You will need to highlight the column or cell and change the format to Number>Rounded to get rid of it.
I am sure i am missing some components of your full script here, however have you tried the "getLastRow" function? There are some scripts in the tutorials that use it and it is a tried tested and true method of finding the last row of the sheet.