Skip to main content
Lordrhavin
Inspiring
August 11, 2023
Answered

app.changeGrepPreferences.changeTo to a callback?

  • August 11, 2023
  • 2 replies
  • 613 views

I can use app.changeGrepPreferences.changeTo = "$1"; to insert the first match of  app.findGrepPreferences.findWhat. But how can I do this per found item as a call to a function? Can I give it a callback, and if yes: how..?

This topic has been closed for replies.
Correct answer Lordrhavin

OK, I dont know if there is a solution with changeTo, but I found a simple solution with findGrep and iteration thru the results:

	app.findGrepPreferences.findWhat = "\{\{[^:]*\:[^}]*\}\}";
	var hits = app.activeDocument.findGrep();
	for (var i = 0; i < hits.length; i++) {
 		hits[i].contents = hits[i].contents.replace(/\{\{([^:]*)\:([^}]*)\}\}/g,callback_function_here);
	}

2 replies

Robert at ID-Tasker
Legend
August 11, 2023

What EXACTLY are you trying to achieve? 

 

Lordrhavin
LordrhavinAuthorCorrect answer
Inspiring
August 11, 2023

OK, I dont know if there is a solution with changeTo, but I found a simple solution with findGrep and iteration thru the results:

	app.findGrepPreferences.findWhat = "\{\{[^:]*\:[^}]*\}\}";
	var hits = app.activeDocument.findGrep();
	for (var i = 0; i < hits.length; i++) {
 		hits[i].contents = hits[i].contents.replace(/\{\{([^:]*)\:([^}]*)\}\}/g,callback_function_here);
	}
m1b
Community Expert
Community Expert
August 11, 2023

Hi @Lordrhavin, that is the normal way I think. However, bear in mind that editing the contents will replace any textStyleRanges in hits[i] with the styling of the first textStyleRange of hits[i]. So if you find "ABC" and the "B" is bold, you will lose that bold style and "ABC" will be styled to match "A". If this is a problem in your case, you can simply do a second changeGrep (or multiple changeGreps) on the found text, eg. hits[i].changeGrep().

- Mark

Lordrhavin
Inspiring
August 11, 2023

I just ound out it is even worse: if I have the fifth char of my search text in bold, i end up with the fifth cha of my replace text in bold. How can I give the whole replacement text the style of the first search char? Because: that would be great!