2025-02-14- javascript一般字串與樣板字串

2025-02-14- javascript一般字串與樣板字串


🔍 1. 單引號('...')或雙引號("...")是 一般字串

像這樣:

1
const apiKey = 'ABC1234567';

這是普通的文字字串,不能插入變數。


🔍 2. 反引號(`...`)是 Template Literal(樣板字串)

1
const url = `https://api.com?key=${apiKey}`

這是 JavaScript 的「樣板字串」,它有一個強大功能:

✅ 可以用 ${變數} 插入變數或表達式:

1
2
const name = 'Lily'
const message = `Hello, ${name}!` // ➜ "Hello, Lily!"

📌 小結對照表

語法 名稱 是否可插入變數(${}
'...' 單引號字串 ❌ 不行
"..." 雙引號字串 ❌ 不行
`...` 樣板字串(Template Literal) ✅ 可以!

✅ 實戰對照

1
2
3
4
5
6
7
8
const apiKey = 'abc123'
const city = 'Taipei'

// 錯誤寫法:這樣 city 不會被插入
const url1 = 'https://api.com/data?city=${city}'

// 正確寫法:用反引號
const url2 = `https://api.com/data?city=${city}`