简体   繁体   English

在JS模板字符串中转义$ {}的正确方法

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

I am creating a bash command: 我正在创建一个bash命令:

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. 它在${序列前面加上前缀,否则将被解释为定界符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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