I need to create a google apps script that will insert some string inside the active document. And I need to have the possibility later to know if the user has used the script on the doc and change the text that was already inserted.
Is it possible to tag or insert a custom property/attribute for the string that i am adding?
For example instead of adding
<b>Custom Text</b>
Is it possible to insert this?
<p CustomAttribute=Cust1>Custom Text</p>
Also, How can I search for my custom attribute inside the doc?
You can achieve this type of effect using NamedRanges. Basically, the strategy is to:
Here's a rough implementation of this type of strategy:
function testing() {
// Add a new paragraph within a Named Range
var named = addTextWithNamedRange('This is my added text', 'RangeLabel01');
// NamedRanges can share the same names, but the IDs are unique,
// so use IDs to easily reference specific NamedRanges
var namedId = named.getId();
// Now save this ID to a data structure, along with any other information
// about it you need to record
// Later, when you need to reference that text/paragraph/element,
// use the ID to find it, and make any changes you need:
accessNamedRange(namedId);
}
function addTextWithNamedRange(str, name) {
// Add a new paragraph to end of doc
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.appendParagraph(str);
// Creates a NamedRange that includes the new paragraph
// Return the created Named Range
var rangeBuilder = doc.newRange();
rangeBuilder.addElement(text);
return doc.addNamedRange(name, rangeBuilder.build());
}
function accessNamedRange(rangeId) {
// Determine if a NamedRange with this ID exists
// If it does, log information about it and the Paragraph
// elements it includes
var doc = DocumentApp.getActiveDocument();
var named = doc.getNamedRangeById(rangeId);
if (named) {
var rangeElements = named.getRange().getRangeElements();
for(var r in rangeElements) {
var text = rangeElements[r].getElement().asParagraph().getText();
// Just logging here, but could potentially edit or
// otherwise manipulate the text
Logger.log('Found NamedRange ' + named.getName() +
' (id='+rangeId+') --> ' + text);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With