简体   繁体   中英

Proper way to escape ${} in a JS template string

I am creating a bash command:

const k = cp.spawn('bash');

k.stdin.end(`
  alias ssh='ssh "${SSH_ARGS[@]}"'
`);

but of course, I have to escape it. I assume the best way to escape it, is using:

 `alias ssh='ssh "\${SSH_ARGS[@]}"'`

can anyone explain why that works?

Escaping just the $ works for the same reasons that ordinary curly braces don't throw errors — an expression within a template string is identified by ${ at the beginning and } at the end. If the dollar sign is escaped, it isn't interpreted as part of the ${ keyword, and the curly braces are interpreted as normal characters.

Because the backslash \\ is the escape character as usual, also in template strings. It prefixes the ${ sequence that would otherwise be interpreted as a delimiter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM