# Removing spaces from label generated inside command based on arguments

I have a command which takes two arguments. Inside the command there will be inserted a subsection which also would like to put a label on. The problem is that the arguments might have Spaces between the Words and therefore thay have to be removed before assigning them to the label.

A MCE looks like this:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{hyperref}

\newcommand{\createPerson}[2]
{
\subsection{#1}
\label{#1#2}
Use of the original #1 and #2 again.
}

\begin{document}
\createPerson{Hans Viggo Jensen}{1956}

See the reference \ref{HansViggoJensen1956}, \nameref{HansViggoJensen1956}.
\end{document}

• \\ref{Hans Viggo Jensen1956} works, why do you need to remove the spaces? – Torbjørn T. Sep 13 '15 at 10:59
• @TorbjørnT. Sorry my falut. I thourght that it was a problem with the Spaces because it could't find the reference. But now I realize that I referenced it without Spaces :S – 7heViking Sep 13 '15 at 11:06
• as egreg hints in his answer it is a bad idea generally to mix the internal identifier used by label with anything that is to be typeset. It would be better to give your command another argument for the label (and don't forget % at ends of lines:-) – David Carlisle Sep 13 '15 at 11:19

Don't do it. Don't do it.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{hyperref}

\makeatletter
\newcommand{\createPerson}[2]{%
\subsection{#1}%
\label{\zap@space#1 \@empty #2}%
Use of the original #1 and #2 again.
}
\makeatother

\begin{document}

\createPerson{Hans Viggo Jensen}{1956}

See the reference \ref{HansViggoJensen1956}, \nameref{HansViggoJensen1956}.

\end{document}


But then try this with

Preben Elkjær Larsen


and you will understand why you should never do this.

And no, leaving the spaces in the argument to \ref and your unmodified code won't do either.

Labels should be just easy mnemonics. In case your references are mostly without special letters, you can obviate to the problem by adding an optional argument:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{xparse}
\usepackage{hyperref}

\ExplSyntaxOn

\tl_new:N \l_firefly_label_tl

\NewDocumentCommand{\createPerson}{omm}
{
\IfValueTF{#1}
{% use the optional argument, if present
\tl_set:Nn \l_firefly_label_tl { #1 #3 }
}
{% otherwise, strip spaces
\tl_set:Nn \l_firefly_label_tl { #2 #3 }
\tl_replace_all:Nnn \l_firefly_label_tl { ~ } { }
}
\subsection{#2}
\label{\l_firefly_label_tl}
Use ~ of ~ the ~ original ~ #2 ~ and ~ #3 ~ again.
}
\ExplSyntaxOff

\begin{document}

\createPerson{Hans Viggo Jensen}{1956}

See the reference \ref{HansViggoJensen1956}, \nameref{HansViggoJensen1956}.