如何在 JavaScript 中进行字符串插值?
javascriptobject oriented programmingprogramming
JavaScript 中的字符串插值是将表达式插入或放置在字符串中的过程。要将此表达式插入或嵌入到字符串中,需要使用模板文字。通过在 JavaScript 中使用字符串插值,还可以添加变量、数学表达式和计算等值。
模板文字有一个美元符号,后跟大括号。在此模板文字的大括号内,应写入要评估和嵌入的表达式或数学计算。
语法
JavaScript 中字符串插值的语法如下。
`应在反引号中括起插值的字符串:表达式`
在 JavaScript 中,通过使用字符串插值,可以使用占位符将输入动态插入到字符串的各个部分。将变量插入字符串的传统方法不支持动态插入输入的可能性。
示例 1
此示例演示了如何使用模板文字在 JavaScript 中插入字符串。
const name="Abdul Rawoof" const company = "Tutorials Point" let salary = 18000 let increment = 2000 let mail = 'abdul@gmail.com' console.log(`Employee name is ${name} and the company is ${company} Salary of ${name} after increment is ${increment}:${salary+increment} Contact details of ${name} is ${mail}`)
示例 1 的传统代码如下,
const name="Abdul Rawoof" const company = "Tutorials Point" let salary = 18000 let increment = 2000 let mail = 'abdul@gmail.com' console.log("Employee name is" +name + "and the company is" +company) console.log("Salary of "+ name + "after increment "+ increment +" is "+(salary+increment)) console.log("Contact details of "+ name + "is "+mail)
上述代码是传统方式,与示例 1 代码相比,行数更多。传统方式下,控制台命令必须编写 3 次,但使用反引号和占位符时,只需在一个控制台中编写。这降低了代码复杂性,并且可以使用动态输入。
可以使用字符串插值来执行合并字符串、进行数学计算、使用三元运算符等。
示例 2
此示例演示了 JavaScript 中字符串插值可以执行的一些操作。
const name1="Abdul" const name2="Rawoof" name = `${name1+name2}` const company = "Tutorials Point" let salary = 18000 let increment = 2000 let mail = 'abdul@gmail.com' let experience = 3 console.log("String Concate: Full name is",`${name1 + name2}`) console.log("String Interpolation",`Employee name is ${name} and the company is ${company}`) console.log("Using Ternary Operator",`Salary if increment is done based on experience ${experience > 2 ? 20000 : 18000}`)