What does ${} (dollar sign and curly braces) mean in a string in Javascript?

时光怂恿深爱的人放手 提交于 2019-12-17 03:46:40

问题


I haven't seen anything here or on MDN. I'm sure I'm just missing something. There's got to be some documentation on this somewhere?

Functionally, it looks like it allows you to nest a variable inside a string without doing concatenation using the + operator. I'm looking for documentation on this feature.

Example:

var string = 'this is a string';

console.log(`Insert a string here: ${string}`);

回答1:


You're talking about template literals.

They allow for both multiline strings and string interpolation.

Multiline strings:

console.log(`foo
bar`);
// foo
// bar

String interpolation:

var foo = 'bar';
console.log(`Let's meet at the ${foo}`);
// Let's meet at the bar



回答2:


As mentioned in a comment above, you can have expressions within the template strings/literals. Example:

const one = 1;
const two = 2;
const result = `One add two is ${one + two}`;
console.log(result); // output: One add two is 3


来源:https://stackoverflow.com/questions/35835362/what-does-dollar-sign-and-curly-braces-mean-in-a-string-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!