如何在 JavaScript 中進行字串插值?
JavaScript 字串插值是一個將表示式插入或放置到字串中的過程。為了將此表示式插入或嵌入到字串中,可以使用模板字面量。透過在 JavaScript 中使用字串插值,還可以新增變數、數學表示式和計算結果等值。
模板字面量包含一個美元符號後跟花括號。在這個模板字面量的花括號內,應該編寫要計算和嵌入的表示式或數學計算。
語法
JavaScript 字串插值的語法如下所示。
`string where interpolation should be done enclosed in backticks: expression`
在 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}`)
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP