I need to get rid of mulitple instances of hyperlinked text ", foo bar" in my compiled latex document. It would be incredibly laborious to employ global find and replace on source code because each instance of the string has different code due to hyperlinking. Also, I would like to easily turn instances of the string off and on.
I have tried using lualatex based on an answer from @Mico at
https://tex.stackexchange.com/questions/213947/how-to-replace-text
Thus:
\documentclass[10pt]{article}
% !TEX TS-program = lualatex
\usepackage{luacode}
\begin{luacode}
function myreplace1 ( s )
s = s:gsub ( ", Foo Bar" , "" )
return s
end
\end{luacode}
\AtBeginDocument{\directlua{luatexbase.add_to_callback(%
"process_input_buffer", myreplace1 , "myreplace1")}}
\usepackage{hyperref}
\begin{document}
The Foo Bar at the end of this sentence disappears thanks to myreplace1, Foo Bar.
While this does not, \textbf{\hyperref[sec:Interesting]{Foo Bar}}.
Though, oddly a version of myreplace1 that uses "Foo Bar" without the comma (s = s:gsub ( "Foo Bar" , "" )) works fine with \textbf{\hyperref[sec:Interesting]{Foo Bar}}.
\section{Interesting words} \label{sec:Interesting}
\end{document}
The approach works using hyperlinked "foo bar", but not if the hyperlinked "foo bar" is preceeded with a comma and space ", foo bar", in which case the string is left unmolested in the compiled text. As far as I can tell, commas and spaces are not "magic" in lua. In any event using escape characters such as %, \\ and [[ ]] do not seem to have any effect on the final result.
Many thanks for your help!

\documentclass{article}immediately before\usepackage{luacode}and adding\begin{document},Hello, foo bar World, and\end{document}on three separate lines at the end. I.e., LuaLaTeX outputsHello World; put differently, the string, foo bar-- including the leading comma-whitespace substring -- is removed successfully from the input stream. Please augment your code snippet to produce an example in which the Lua function fails to operate as expected. – Mico Jun 19 '20 at 03:00