🔗
← 返回教學列表

JavaScript 中的 URL 編碼——encodeURI、encodeURIComponent 與最佳實踐

· 標籤: javascript, url-encoding, encodeURIComponent, encodeURI, programming

JavaScript 提供了兩個內建函數用於 URL 編碼:

encodeURIComponent()

編碼除以下之外的所有字元:A-Z a-z 0-9 - _ . ! ~ * ' ( )

const name = 'John Doe'
const query = '?name=' + encodeURIComponent(name)
// ?name=John%20Doe

用於編碼個別的查詢參數值、路徑片段,或任何成為 URL 一部分的資料。

encodeURI()

編碼除上述字元之外的所有字元,再加上保留的 URL 字元:: / ? # [ ] @ ! $ & ' ( ) * + , ; =

const url = 'https://example.com/search?q=hello world'
const encoded = encodeURI(url)
// https://example.com/search?q=hello%20world

用於編碼完整的 URL 字串。

常見陷阱

// 錯誤——破壞了 URL 結構
encodeURIComponent('https://example.com/page')
// https%3A%2F%2Fexample.com%2Fpage

// 正確——保留了結構
encodeURI('https://example.com/page')
// https://example.com/page

使用我們的 URL 編碼器/解碼器工具即時測試這些函數。

JavaScript 中的 URL 編碼——encodeURI、encodeURIComponent 與最佳實踐 - CoolTool