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})`);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745631185a4637117.html
评论列表(0条)