# How to make macro created with NewDocumentCommand to work when used inside an argument?

I am trying to use the following code to replace \_ with _. Now, this will work:

\documentclass[]{article}

\usepackage{graphicx}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\replacepath}{m}
{
\tl_set:Nn \l__maxd_argument_tl { #1 }
\tl_replace_all:Nnn \l__maxd_argument_tl { \_ } { _ }
\tl_use:N \l__maxd_argument_tl
}
\tl_new:N \l__maxd_argument_tl
\ExplSyntaxOff

\begin{document}

\replacepath{This\_is\_a\_test}

\end{document}


but this does not:

\documentclass[]{article}

\usepackage{graphicx}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\replacepath}{m}
{
\tl_set:Nn \l__maxd_argument_tl { #1 }
\tl_replace_all:Nnn \l__maxd_argument_tl { \_ } { _ }
\tl_use:N \l__maxd_argument_tl
}
\tl_new:N \l__maxd_argument_tl
\ExplSyntaxOff

\begin{document}

\includegraphics{\replacepath{This\_is\_a\_test}}

\end{document}


The latter gives following error:

(c:/texlive/2018/texmf-dist/tex/latex/l3kernel/l3xdvipdfmx.def))) (./test.aux)
! Missing \endcsname inserted.
\cs_set_nopar:Npx
l.19 ...egraphics{\replacepath{This\_is\_a\_test}}


## Questions

• What should I change to make the \replacepath to work when used as an argument for the \includegraphics?
• Why does the second case not work? I would expect the
\includegraphics{\replacepath{This\_is\_a\_test}}


to be replaced with

\includegraphics{This_is_a_test}


which I would assume to include a figure called This_is_a_test into the document.

• Sorry, but it cannot work: the argument to \includegraphics should be a file name, not the instructions to print one. Why aren't you simply using This_is_a_test as the file name? Jun 14, 2020 at 19:44
• The .tex file is coming as an output from pandoc. The backslashes are added automatically, and I was searching for a way to correct the \_ back to _. Is is possible to create a macro to output a string for the includegraphics (and not instructions to print one)?
– np8
Jun 14, 2020 at 19:50