admin管理员组文章数量:1434921
I want to write backtick inside backtick. (es6)
How do you create backtick in backtick ?
const apple = 'apple';
const grape = 'grape';
const money1 = 2000;
const money2 = 1000;
// before
console.log(`${apple} = ${grape === 'grape' ? '(' + money1 + ')' : '(' + money2 + ')'`;
// after <-- I want
console.log(`${apple} = ${grape === 'grape' ? \`(${money1})\` : \`(${money2})\`}`;
I want to write backtick inside backtick. (es6)
How do you create backtick in backtick ?
const apple = 'apple';
const grape = 'grape';
const money1 = 2000;
const money2 = 1000;
// before
console.log(`${apple} = ${grape === 'grape' ? '(' + money1 + ')' : '(' + money2 + ')'`;
// after <-- I want
console.log(`${apple} = ${grape === 'grape' ? \`(${money1})\` : \`(${money2})\`}`;
Share
Improve this question
edited Jun 13, 2019 at 0:35
Jack Bashford
44.2k11 gold badges55 silver badges82 bronze badges
asked Jun 13, 2019 at 0:30
KimBenGonKimBenGon
3155 silver badges12 bronze badges
1
- Your question isn't very clear. What do you want the actual log message to look like? – Barmar Commented Jun 13, 2019 at 0:42
3 Answers
Reset to default 4Remove the backslashes:
const apple = 'apple';
const grape = 'grape';
const money1 = 2000;
const money2 = 1000;
console.log(`${apple} = ${grape === 'grape' ? `(${money1})` : `(${money2})`}`);
If you were asking about printing a literal backpack in a template string, then just use a backslash normally.
console.log(`\``);
To answer your question literaly: "to put a backtick in backticks" sounds like how to put a literal backtick into a string. To do that, escape it.
Escape it with a backslash. See https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Template_literals#Description
`\``
console.log(`\``)
But what you actually are trying to do is not so plex. The JavaScript syntax allows for nesting backticks within ${} without escaping them.
console.log(`Hello ${`world`}, ${`nesting ${`works too`}`}`);
I realize that your example is partially hypothetical, but there's a much simpler approach to your example that avoids the need for nested template literals:
const apple = 'apple';
const grape = 'grape';
const money1 = 2000;
const money2 = 1000;
console.log(`${apple} = (${grape === 'grape' ? money1 : money2})`);
本文标签: javascriptHow do I create backtick in backticksStack Overflow
版权声明:本文标题:javascript - How do I create backtick in backticks? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745631185a2667282.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论