I'm having a similar problem as described here: How to use \newcommand for \href?

However, I want to specify an URL with an # sign in it. I know that I should escape the # by \#, but as we have many links containing the #, it may be nice to be able to copy and paste the URL directly into the LaTeX code.

My current solution looks like this:



\myhref{somewhere} % WORKS
\myhref[LINK TEXT]{somewhere} % WORKS

\myhref{somewhere\#anchor} % WORKS
\myhref[LINK TEXT]{somewhere\#anchor} % WORKS

\myhref{somewhere/#anchor} % WORKS NOT - BUT I WANT IT TO WORK !!!
\myhref[LINK TEXT]{somewhere#anchor} % WORKS NOT - BUT I WANT IT TO WORK !!!

Is there a way to automatically escape the # character in the argument to \myhref?

1 Answer 1


You have to absorb the # as a "normal character"


The package hyperref does a good job with these strange characters, but here the problem is that when you say \myhref{somewhere#anchor} the # has already been absorbed by TeX with category code 6, which breaks \href.

Here we tell LaTeX to open a group in which # will be considered as a normal character and only after this we absorb the arguments.

  • Thank you very much! I have experimented with \catcode'\#=\somenumber a bit but I think I have tried to make # a letter (catcode 11). Commented Nov 18, 2011 at 17:26
  • @WolfgangUlmer That would break the use of \#anchor which would become a unique control sequence.
    – egreg
    Commented Nov 18, 2011 at 17:37
  • Yes. That has been my problem. I could make one of the two variants work but not both. Your solution works with both syntax variants. Commented Nov 18, 2011 at 17:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .