Gobbling an argument if it starts with #
Here is an idea for a conditional
\iffirsttoken{<tokenlist>}{<token>}{<true>}{<false>}
using the kernel command \@car
. You can use it in your redefinition of \href
to test whether the first token is \#
:
\documentclass{article}
\makeatletter
% this is found in latex.ltx:
% \def\@car#1#2\@nil{#1}
\def\iffirsttoken#1#2{%
% define \@first@token to be the once expanded \@car of the first argument
% i.e. the first token or balanced group:
\expandafter\def\expandafter\@first@token\expandafter{\@car#1\@nil}%
% test if the expansion of \@first@token is the same as #2:
\expandafter\ifx\@first@token#2\relax
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
}
\usepackage{hyperref}
\let\oldhref\href
\renewcommand{\href}[2]{%
\oldhref{#1}{#2}%
\iffirsttoken{#1}{\#}{}{\footnote{\url{#1}}}%
}
\begin{document}
\hyperdef{}{related-work}{\section{Related work}\label{related-work}}
\iffirsttoken{foo}{f}{true}{false}% true
\iffirsttoken{\#related-work}{\#}{true}{false}% true
\iffirsttoken{this web}{\#}{true}{false}% false
\href{http://tex.stackexchange.com}{this web}
\href{\#related-work}{section about related work}
\end{document}
If you are looking to strip \# from the first position of a string, it can be done simply with this command
\newcommand\strippound[1]{\expandafter\ifx\expandafter\##1\else#1\fi}
Now stripping a # is a different beast, because it is a special character in TeX
After a day of reflection, I had an idea on how to strip an actual # sign (not a \# sign, mind you) from the first character of a string. This is a significant result, I think, given how difficult is is for TeX to operate on the # character. In the end, the answer was amazingly simple. Here it is:
\documentclass{article}
\catcode `#=11
\edef\lb{#}
\catcode `#=6
\newcommand\strippound[1]{\if\lb#1\else#1\fi}
\begin{document}
\noindent
\strippound{#This string began with a pound sign}\\ \strippound{This string did not begin with a pound sign}
\end{document}