如何忽略特定的字符串插值并在 JavaScript 模板文字中使用纯文本?
Howto ignore specific string interpolation and use plain text in JavaScript template literals?
我必须通过代码设置配置文件并传入一些变量
const confEntry = String.raw`
[${internal}]
...
user = bg${internal}
auth_user = bg${internal}
...
secret = ${password}
...
from_sip_src_setting=from_display,sip_from_user_setting=${account_username}
...
`;
说到
from_sip_src_setting=from_display,sip_from_user_setting=${account_username}
我不想传入变量。 =${account_username}
应该写成纯文本。显然我得到了错误
account_username is not defined
我怎样才能忽略这个并为这个特定部分写纯文本?
如果您想在最终字符串中保留 ${}
,您可以使用反斜杠 \
转义美元符号、花括号或两者,这会破坏 ${}
模式,它将被视为常规文本:
const world = 'world';
console.log(`${hello} $\{world\} $\{hello\} ${world}`);
However, since String.raw
escapes everything, you cannot use that trick.
但是,使用上面的技巧,您可以使用这样的内部模板字符串生成 ${str}
字符串:
const world = 'world';
const raw = x => `${${x}}`;
console.log(String.raw`${raw('hello')} ${world}`);
或者简单地说:
const world = 'world';
const raw = x => '${' + x + '}';
console.log(String.raw`${raw('hello')} ${world}`);
您需要转义花括号,以免它被解释为字符串文字
所以 ${account_username}
应该是 $\{account_username\}
String.raw used to get the raw string form of template
strings, that is, substitutions (e.g. ${foo}) are processed, but
escapes (e.g. \n) are not.
String.raw 不处理你的转义。
let a = String.raw`hello\nhow are you`
let b = `hello\nhow are you`
console.log(a) //raw string output
console.log(b) // template string output
我必须通过代码设置配置文件并传入一些变量
const confEntry = String.raw`
[${internal}]
...
user = bg${internal}
auth_user = bg${internal}
...
secret = ${password}
...
from_sip_src_setting=from_display,sip_from_user_setting=${account_username}
...
`;
说到
from_sip_src_setting=from_display,sip_from_user_setting=${account_username}
我不想传入变量。 =${account_username}
应该写成纯文本。显然我得到了错误
account_username is not defined
我怎样才能忽略这个并为这个特定部分写纯文本?
如果您想在最终字符串中保留 ${}
,您可以使用反斜杠 \
转义美元符号、花括号或两者,这会破坏 ${}
模式,它将被视为常规文本:
const world = 'world';
console.log(`${hello} $\{world\} $\{hello\} ${world}`);
However, since
String.raw
escapes everything, you cannot use that trick.
但是,使用上面的技巧,您可以使用这样的内部模板字符串生成 ${str}
字符串:
const world = 'world';
const raw = x => `${${x}}`;
console.log(String.raw`${raw('hello')} ${world}`);
或者简单地说:
const world = 'world';
const raw = x => '${' + x + '}';
console.log(String.raw`${raw('hello')} ${world}`);
您需要转义花括号,以免它被解释为字符串文字
所以 ${account_username}
应该是 $\{account_username\}
String.raw used to get the raw string form of template strings, that is, substitutions (e.g. ${foo}) are processed, but escapes (e.g. \n) are not.
String.raw 不处理你的转义。
let a = String.raw`hello\nhow are you`
let b = `hello\nhow are you`
console.log(a) //raw string output
console.log(b) // template string output