TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 12 down vote accepted

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.

share|improve this answer
Thank you very much! I have experimented with \catcode'\#=\somenumber a bit but I think I have tried to make # a letter (catcode 11). – Wolfgang Ulmer Nov 18 '11 at 17:26
@WolfgangUlmer That would break the use of \#anchor which would become a unique control sequence. – egreg Nov 18 '11 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. – Wolfgang Ulmer Nov 18 '11 at 17:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.