向 javascript 字符串插值的结果字符串添加一对反引号的优雅方法?
Elegant way to add a pair of back ticks to the resulting string from javascript string interpolation?
我正在使用字符串插值来创建要发送到其他服务的字符串。此其他服务允许在显示文本时使用反引号来格式化文本。我想在此字符串中包含反引号,以便最终用户更易读。
我找到了一个的方法,但是好像很草率。我需要 6 个字符才能将 1 个字符添加到我的输出中,并在键盘上发送我的小指,因此难以键入:
const myString = `There will be one here -> ${'`'} and one here -> ${'`'}.`;
// There will be one here -> ` and one here -> `.
我有更好的方法吗?
您可以使用反斜杠对其进行转义:
To escape a back-tick in a template literal, put a backslash \ before the back-tick. - MDN
const myString = `There will be one here -> ${'`'} and one here -> ${'`'}.`;
const myString2 = `There will be one here -> \` and one here -> \`.`;
console.log(myString === myString2);
我正在使用字符串插值来创建要发送到其他服务的字符串。此其他服务允许在显示文本时使用反引号来格式化文本。我想在此字符串中包含反引号,以便最终用户更易读。
我找到了一个的方法,但是好像很草率。我需要 6 个字符才能将 1 个字符添加到我的输出中,并在键盘上发送我的小指,因此难以键入:
const myString = `There will be one here -> ${'`'} and one here -> ${'`'}.`;
// There will be one here -> ` and one here -> `.
我有更好的方法吗?
您可以使用反斜杠对其进行转义:
To escape a back-tick in a template literal, put a backslash \ before the back-tick. - MDN
const myString = `There will be one here -> ${'`'} and one here -> ${'`'}.`;
const myString2 = `There will be one here -> \` and one here -> \`.`;
console.log(myString === myString2);