URL 編碼與解碼
對 URL 字串進行編碼與解碼,安全處理特殊字元與非 ASCII 文本,適用於查詢參數與路徑傳輸。
使用說明
URL 編碼會將特殊字元或非 ASCII 字元轉換為 %XX 格式,以便在 URL 中安全傳輸。
使用「編碼」將文字轉換為適用於 URL 的安全形式(例如查詢參數)。
使用「解碼」將 %XX 序列還原為原始字元。
常見情境:處理查詢參數、表單資料傳輸、API 調用等。
功能特性
- 兩種編碼模式:encodeURIComponent 與 encodeURI
- 靈活的空格處理:編碼為 + 或 %20
- 即時轉換並顯示輸入/輸出長度統計
- 複製/清空按鈕與雙向傳送至對方面板
- 完整的國際化與 DaisyUI 多主題支援
什麼是 URL 編碼
URL 編碼將字元轉換為 %XX 百分比編碼序列,以便在 URL 中安全傳輸。
encodeURIComponent 適用於單個元件(如單一查詢參數值),會編碼絕大多數非字母數字字元。
encodeURI 適用於完整的 URI 字串,不會編碼 ?、&、=、\/ 等具有結構意義的保留字元。
常見問題與陷阱
- encodeURI 與 encodeURIComponent:參數使用 component,完整連結使用 URI
- 空格與 +:application/x-www-form-urlencoded 在查詢字串中常用 + 表示空格
- 避免重複解碼:多次解碼會損壞資料
- 無效的百分比序列會拋出錯誤;需妥善處理異常
如何在程式語言中進行 URL 編解碼
JavaScript
編碼
// Component (recommended for query values)
const encoded = encodeURIComponent(text);
// If you need '+' for spaces in query strings
const encodedPlus = encoded.replace(/%20/g, '+');
// Full URI
const encodedUri = encodeURI(url);
解碼
// Treat '+' as space if needed
const input = plusAsSpace ? s.replace(/\+/g, ' ') : s;
// Component
const dec1 = decodeURIComponent(input);
// Fallback to decodeURI when input is a full URL
const dec2 = decodeURI(input);
PHP
編碼
// Component (RFC 3986)
$encoded = rawurlencode($text);
// '+' for spaces (application/x-www-form-urlencoded)
$encodedPlus = str_replace('%20', '+', $encoded);
// Full query usage
$query = http_build_query(['q' => '你好 世界', 'type' => 'text']);
解碼
// Component
$decoded = rawurldecode($s);
// If input uses '+' for spaces
$decodedPlus = urldecode($s);
Python
編碼
from urllib.parse import quote, quote_plus
# Component (RFC 3986)
enc = quote(text, safe='')
# '+' for spaces (application/x-www-form-urlencoded)
enc_plus = quote_plus(text)
解碼
from urllib.parse import unquote, unquote_plus
# Component
dec = unquote(s)
# Input with '+' for spaces
dec_plus = unquote_plus(s)
Go
編碼
import (
"net/url"
)
// Query component
enc := url.QueryEscape(text) // spaces => +
// Path segment
// go1.8+
// url.PathEscape(text)
解碼
import (
"net/url"
)
// Query component
dec, _ := url.QueryUnescape(s)
// Path segment
// url.PathUnescape(s)
Rust
編碼
// Cargo.toml: urlencoding = "^2"
use urlencoding::{encode, encode_binary};
let enc = encode(text); // component; spaces => %20
let enc_plus = enc.replace("%20", "+"); // if you need '+' for spaces
解碼
use urlencoding::decode;
// decode treats '+' as space
let dec = decode(s)?; // Result, _>
Java
編碼
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
// Query param / form style (spaces => '+')
String enc = URLEncoder.encode(text, StandardCharsets.UTF_8);
// For RFC3986-like component encoding, replace '+' with %20 if needed
String encSpace = enc.replace("+", "%20");
解碼
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
// URLDecoder treats '+' as space
String dec = URLDecoder.decode(s, StandardCharsets.UTF_8);