Skip to main content
Participant
April 2, 2020
Answered

How to retain rich formatting when replacing in comments using Javascript?

  • April 2, 2020
  • 1 reply
  • 565 views

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)	
		}
	}
}

 

This topic has been closed for replies.
Correct answer try67

You need to re-apply the array of Spans to the richContents property as a whole, not one by one.

1 reply

try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
April 2, 2020

You need to re-apply the array of Spans to the richContents property as a whole, not one by one.

Min_NAuthor
Participant
April 7, 2020

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
	}
}