The most efficient and safest way is to use Dokuwiki's AJAX_CALL_UNKNOWN event:
https://www.dokuwiki.org/devel:event:ajax_call_unknown
You set up an ajax call to dw's ajax library which then gets retrieved in the AJAX_CALL_UNKNOWN event handler where you can process as you wish. The call can be made from a link or by means of any other determinants, enabling you to insert text wherever you need it. But there's nothing preventing you from calling your own scripts in a similar manner and, for instance, using jQuery to modify your text.