How to expand or detokenize a macro before using it in a hyperlink

detokenizeexpandafterhyperref

So I have some information stored in a macro that is used already elsewhere and can contain formatting macros like \small or similar and I want to expand or detokenize those commands before also using the content for the subject of a hyperlink. This is what I expected to work:

\documentclass{article}
\usepackage{hyperref}

\def\subject{\small This is my subject}

\begin{document}
    \href{mailto:[email protected]?subject=\expandafter\detokenize{\subject}}{Send an email}
\end{document}

However in this case \subject is never expanded, as you can see from the PDF viewer:

enter image description here

So what is the appropriate way of expanding \subjectand thereby get rid of the \small?

Best Answer

Much like Jinwin's answer but using the expandable text expander in expl3:

\documentclass{article}
\ExplSyntaxOn
\cs_new_eq:NN \PurifyText \text_purify:n
\ExplSyntaxOff

\usepackage{hyperref}

\def\subject{\small This is my subject}

\begin{document}

\href{mailto:[email protected]?subject=\detokenize\expandafter{\expanded{\PurifyText{\subject}}}}{Send an email}

\end{document}

Here \text_purify:n does remove formatting.

Related Question