」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > JavaScript 中的字串插值。

JavaScript 中的字串插值。

發佈於2024-11-03
瀏覽:762

String Interpolation in JavaScript.

範本文字簡介。

字串操作是程式設計中非常常見的任務,尤其是在建立互動式 Web 應用程式時。如果您曾經花時間使用 JavaScript,那麼您可能必須將一些變數放入字串中。
在舊版本的 JavaScript 中,這意味著使用運算子透過稱為 字串連接 的過程將字串連接在一起。然而,隨著 JavaScript ES6(2015) 更新中引入 範本文字 。我們現在有一種更簡潔的方法將變數插入字串,稱為 字串插值.

什麼是模板文字?

模板文字使我們能夠更輕鬆地操作字串。它們用反引號 (`) 而不是 (') 或 (") 括起來,並且它們透過使用 (${}) 語法將變數或函數呼叫直接放入字串中來支援字串插值。

這是範本文字如何簡化字串插值的範例。

const name = "John"
const age = 24

// Old method using concatenation
const greeting = "Hello, "   name   "! You are "   age   " years old."

// New method using template literals
const greetingWithTemplateLiteral = `Hello, ${name}! You are ${age} years old.`

console.log(greetingWithTemplateLiteral) // Outputs: Hello, John! You are 24 years old.

使用模板文字的好處

1. 提高可讀性

使用字串連接時,很容易迷失在一堆符號中,尤其是在處理較長的字串時。模板文字透過讓您以更容易理解的方式編寫字串來避免這種情況。

const product = "laptop"
const price = 1400

console.log(`The price of the ${product} is $${price}`)
// Outputs: The price of the laptop is $1400

2. 多行字串

在範本文字之前,您必須使用 \n 等轉義字元來產生多行字串。現在你可以將它們寫在反引號(`)中。

// Old method
const multiLineString1 = "This is the first line"   "\n"   "This is the second line"   "\n"   "This is the third line"

// New method
const multiLineString2 = `This is the first line
This is the second line
This is the third line`

console.log(multiLineString1)
console.log(multiLineString2)
/* Both output:
This is the first line
This is the second line
This is the third line
*/

3. 表達式求值

您也可以執行計算、呼叫函數或操作字串內的資料。

const a = 1
const b = 10

console.log(`The sum of a and b is ${a   b}`) 
// Outputs: The sum of a and b is 11

const upperCaseName = (name) => name.toUpperCase()
console.log(`Your name in uppercase is ${upperCaseName("John")}`)
// Outputs: Your name in uppercase is JOHN

JavaScript 中的常見用例

1. HTML生成

您可以透過插值將變數直接放入字串中,而不是透過連接來建立 HTML 字串。

const name = "John"
const htmlContent = `
  

Hello, ${name}!

Welcome to the site.

`

2. 記錄訊息

您也可以將變數直接插入日誌訊息中,無需連線。

const user = "John"
const action = "logged in"

console.log(`User ${user} just ${action}`)
// Outputs: User John just logged in

3. 建立 URL

模板文字也讓建構 URL 變得更容易。

const userId = 123
const apiUrl = `https://api.example.com/user/${userId}/details`

console.log(apiUrl)
// Outputs: https://api.example.com/user/123/details

4. 條件邏輯

另一個很好的用例是條件邏輯。透過範本文字,您可以使用三元運算子 (? :) 為字串提供簡單條件,這是 if-else 條件的簡寫。
邏輯運算符,如 &&(與)或 || (or) 也可用於在字串中新增條件部分。這消除了額外的 if-else 語句或連接的需要。

const isMember = true
console.log(`User is ${isMember ? 'a member' : 'not a member'}`) 
// Outputs: User is a member

您也可以在範本文字中加入更複雜的表達式。

/* In this example, the condition age >= 18 is evaluated
the result is either “an adult” or “a minor” based on the value of age*/
const age = 24

const message = `You are ${age >= 18 ? 'an adult' : 'a minor'}`

console.log(message) 
// Outputs: You are an adult

/*In this, if isLoggedIn is true and username exists
username is displayed or else, it defaults to “Guest” */
const isLoggedIn = true
const username = "John"

const greeting = `Welcome ${isLoggedIn && username ? username : 'Guest'}`

console.log(greeting)
// Outputs: Welcome John

結論

JavaScript 中的範本文字提供了一種更清晰、更有效的方式來處理字串插值。在建立 Web 內容、記錄訊息或建立更具可讀性的程式碼之間,此方法提供了您所需的靈活性。

下次處理變數和字串時,請嘗試使用範本文字。您很快就會明白為什麼它是我使用 JavaScript 的首選方法。

資源

  1. MDN Web 文件 - 範本文字
  2. GitHub - 第一階段審查字串實驗室
  3. W3 學校 - JavaScript 範本字串
版本聲明 本文轉載於:https://dev.to/isaiah2k/string-interpolation-in-javascript-1gpb?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3