Copy link to clipboard
Copied
Hello,
I'm trying to write a function to replace text inside FreeText comments without losing the Rich formatting of said comment. Previously I used a .filter.map(replace) over the getAnnots() array of a document, but this removes any formatting and makes everything use the richDefaults.
The nested for loop I have right now (see below) is returning the correct value in the console, but I can't get it to output to the annotations themselves. Could anyone please help me figure out why?
var replaceItem = "abc123";
var replaceWith = "def456";
var annots = this.getAnnots();
var toReplaceItem = RegExp(replaceItem, 'g');
for(i=0; i < annots.length; i++){
if(annots[i].type == "FreeText" && annots[i].contents.search(toReplaceItem)!= -1){
for(j = 0; j < annots[i].richContents.length; j++){
annots[i].richContents[j].text = annots[i].richContents[j].text.replace(toReplaceItem, replaceWith)
}
}
}
You need to re-apply the array of Spans to the richContents property as a whole, not one by one.
Copy link to clipboard
Copied
You need to re-apply the array of Spans to the richContents property as a whole, not one by one.
Copy link to clipboard
Copied
Thanks a lot for the answer, I've managed to get the function working!
For the reference of anyone searching this up later, the script I have now is as follows:
var replaceItem = "abc123";
var replaceWith = "def456";
this.syncAnnots;
var annots = this.getAnnots();
var toReplaceItem = RegExp(replaceItem, 'g');
for (i = 0; i < annots.length; i++){
if(annots[i].contents.search(toReplaceItem) != -1){
var newAnnot = new Array()
for (j = 0; j < annots[i].richContents.length; j++){
newAnnot.push(annots[i].richContents[j])
}
for (j = 0; j < newAnnot.length; j++){
newAnnot[j].text = newAnnot[j].text.replace(toReplaceItem,replaceWith)
}
annots[i].richContents = newAnnot
}
}