学习现代JavaScript中的字符串插值

185 阅读1分钟

在本教程中,我们将通过使用es6模板字面来学习JavaScript中的字符串插值。

模板字元是用反斜线定义的。

字符串插值

为了插值字符串,我们需要使用反斜线,然后使用${} 语法。

下面是一个例子。

let user= 'gowtham';
console.log(`My name is ${user}`);

输出。

My name is gowtham

在上面的例子中,带有大括号的美元符号${ } ,是一个占位符,用于评估通过的表达式。

其他例子。

let name = 'gowtham';
console.log(`My name is ${name} and id is ${Math.random()}`);

console.log(` sum of 2 and 3 is ${2+3}`) // 5

多行字符串

我们也可以在JavaScript中通过使用回车符创建多行字符串

console.log(`This is  a multiline string
             using template literals`);