[Tex/LaTex] Labeling a text and referencing it later

cross-referencing

Is there a way to attach a label to a string and then refer to that string with a reference?

For example,

\labelText{This is a text that is also a tag}{label:text}

and then refer to this string with \ref{label:text} where the string will serve as a tag itself.

Why I need it? I am writing a pseudo code and using a command go to #line number but the line number might change if I insert extra line in the code.
With referencing this will be avoided.

Best Answer

Something like this? This writes the text explicitly to the .aux file and provides a hyperlink to it. Use \nameref to get the label content, not the label number (which is given by \ref)

With more information a better solution could be given.

\documentclass{article}

\usepackage{blindtext}
\usepackage{hyperref}
\usepackage{nameref}

\newcounter{mylabelcounter}

\makeatletter
\newcommand{\labelText}[2]{%
#1\refstepcounter{mylabelcounter}%
\immediate\write\@auxout{%
  \string\newlabel{#2}{{1}{\thepage}{{\unexpanded{#1}}}{mylabelcounter.\number\value{mylabelcounter}}{}}%
}%
}
\makeatother

\begin{document}
\blindtext[5]

\begin{center}
In \nameref{label:text} we have
\end{center}
\section{First} \label{firstsection}
\blindtext[5]
\labelText{This \textsc{is} a text that is also a tag}{label:text}

\end{document}

enter image description here

Related Question