# How to be able to use the number sign (#) in the URL of an underlined href

This question is very brief: how to be able to use the number sign (#) in the URL of an underlined href?

\documentclass{article}

\usepackage{hyperref}

\begin{document}

1 (without \#, link, underlined) = \underline{\href{http://the-best-URL-in-the-world_without-a-number-sign}{URL without number sign}}

% Un-comment the line below to see the error
2 (with \#, link, underlined) = % \underline{\href{http://the-best-URL-in-the-world_with-a-number-sign-#}{URL with a number sign}}

% For reference, the following works fine
3 (with \#, link, not underlined) = \href{http://the-best-URL-in-the-world_with-a-number-sign-#}{URL with a number sign}

\end{document}


Un-comment where indicated to see the compilation error.

P.S.: This question may or may not be similar to How to include a # sign in a url using the \endnotes package.

Here is a \uhref command for selectively underlining the text:

\documentclass{article}
\usepackage{etoolbox}
\usepackage{hyperref}

\makeatletter
\newif\ifunderlinehref
\DeclareRobustCommand{\uhref}{\underlinehreftrue\href}
{{\Hy@tempb}{#4}}
{{\Hy@tempb}{\ifunderlinehref\underline{#4}\else#4\fi}}
{}{}
{\aftergroup\underlinehreffalse}
{}{}
\makeatother

\begin{document}

\href{http://tex.stackexchange.com/#/!!!}{URL with a number sign}

\uhref{http://tex.stackexchange.com/#/!!!}{URL with a number sign}

\end{document}


If you want all links made by \href underlined, you can use a simpler patch:

\documentclass{article}
\usepackage{etoolbox}
\usepackage{hyperref}

\makeatletter
{{\Hy@tempb}{#4}}
{{\Hy@tempb}{\underline{#4}}}
{}{}
\makeatother

\begin{document}

\href{http://tex.stackexchange.com/#/!!!}{URL with a number sign}

\end{document}


Well, one way to fix the problem is to change the position of the \underline so that it is placed within the second argument of the href. The answer, then, becomes:

\documentclass{article}

\usepackage{hyperref}

\begin{document}

1 (without \#, link, underlined) = \underline{\href{http://the-best-URL-in-the-world_without-a-number-sign}{URL without number sign}}

% Fixed below
2 (with \#, link, underlined) = \href{http://the-best-URL-in-the-world_with-a-number-sign-#}{\underline{URL with a number sign}}

3 (with \#, link, not underlined) = \href{http://the-best-URL-in-the-world_with-a-number-sign-#}{URL with a number sign}

\end{document}