Hey everyone, I’m having trouble with a Google Docs script. I’m trying to fill in a template based on form responses. The first part works fine. It replaces {{Name}} with the person’s name from the form. But when I try to replace other placeholders, I get an error.
Here’s what I’m doing:
// This works
var userName = formResponses[0].getValue();
docContent.replaceText('{{Name}}', userName);
// This doesn't work
var placeholder = // value from spreadsheet
var newValue = // value from form
docContent.replaceText(placeholder, newValue);
The second replaceText() gives me an ‘Invalid argument: searchPattern’ error. Any ideas why? It used to work fine until recently. Could Google have changed something?
I’m wondering if it’s related to regex patterns in the first argument of replaceText(). Has anyone else run into this problem? Any help would be great!
I’ve faced this exact problem recently. It’s frustrating when something that used to work suddenly doesn’t. From my experience, the issue might be related to how Google Docs now handles certain characters in the search pattern.
One workaround I found effective was to use the built-in findText() and replaceText() methods in combination. Here’s what I did:
var placeholder = // value from spreadsheet
var newValue = // value from form
var foundElement = docContent.findText(placeholder);
if (foundElement) {
foundElement.getElement().asText().setText(newValue);
}
This approach seems to be more reliable, especially when dealing with special characters or complex patterns. It first finds the text and then replaces it directly, bypassing some of the quirks in the replaceText() method.
Also, double-check your spreadsheet for any hidden formatting or non-printing characters. They can sometimes cause unexpected behavior. Good luck with your script!
I encountered a similar issue recently. It appears Google may have altered how replaceText() handles certain patterns. One potential solution is to use a regular expression object instead of a string for the search pattern. Try modifying your code like this:
var placeholder = new RegExp(placeholderFromSpreadsheet, ‘g’);
docContent.replaceText(placeholder, newValue);
This approach allows more flexibility with special characters. Additionally, ensure your placeholder values in the spreadsheet don’t contain any hidden characters or formatting that could interfere with the replacement process. If issues persist, consider logging the exact values of placeholder and newValue to verify they’re what you expect.
yo ethan, i’ve run into similar issues. seems like google might’ve tweaked sumthin. have u tried escaping special characters in ur placeholder? like if its got brackets, try \{\{ instead of {{. that fixed it for me. also double check ur spreadsheet values, sometimes weird characters sneak in there n mess things up