URL 編碼/解碼工具

常見問題

什麼是 URL 編碼?

URL 編碼是一種將字符轉換為可以在網際網路上傳輸的格式的方法。URL 只能使用 ASCII 字符集通過網際網路發送。由於 URL 經常包含 ASCII 集之外的字符,因此需要轉換 URL。URL 編碼將不安全的 ASCII 字符替換為「%」後跟兩個十六進制數字。

URL 編碼如何運作?

URL 編碼通過將不安全字符替換為「%」後跟表示該字符 UTF-8 編碼的兩個十六進制數字來運作。例如,空格字符編碼為 %20。URL 不能包含空格,因此它們被替換為加號 (+) 或 %20。其他特殊字符則被替換為對應的 %xx 代碼。

常見需要 URL 編碼的字符

以下是在 URL 中使用時需要 URL 編碼的常見字符:

字符URL編碼說明
Space%20URL中最常見的需要編碼的字符
!%21驚嘆號
"%22雙引號
#%23井號(用於URL片段)
$%24美元符號
%%25百分比符號(URL編碼的跳脫字符)
&%26連字號(URL參數分隔符)
'%27單引號
(%28左括號
)%29右括號
+%2B加號
,%2C逗號
/%2F斜線(URL路徑分隔符)
=%3D等號(URL參數賦值符號)
?%3F問號(URL查詢字串開始符號)

不同程式語言中的 URL 編碼實現

以下是各種程式語言中 URL 編碼和解碼的示例:

Go

package main

import (
    "fmt"
    "net/url"
)

func main() {
    // Encode a URL
    text := "Hello World! Special chars: &?=/";
    encoded := url.QueryEscape(text)
    fmt.Println("Encoded:", encoded)

    // Decode a URL
    decoded, err := url.QueryUnescape(encoded)
    if err == nil {
        fmt.Println("Decoded:", decoded)
    }
}

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

// Function to URL-encode a string
char *url_encode(char *str) {
    char *encoded = malloc(strlen(str) * 3 + 1);
    char *pstr = str;
    char *pbuf = encoded;

    while (*pstr) {
        if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') {
            *pbuf++ = *pstr;
        } else if (*pstr == ' ') {
            *pbuf++ = '+';
        } else {
            sprintf(pbuf, "%%%.2X", *pstr);
            pbuf += 3;
        }
        pstr++;
    }
    *pbuf = '\\0';

    return encoded;
}

int main() {
    char *text = "Hello World! Special chars: &?=/";
    char *encoded = url_encode(text);

    printf("Original: %s\\n", text);
    printf("Encoded: %s\\n", encoded);

    free(encoded);
    return 0;
}

PHP

<?php
// URL encoding
$text = "Hello World! Special chars: &?=/";
$encoded = urlencode($text);
echo "Encoded: " . $encoded . "\\n";

// URL decoding
$decoded = urldecode($encoded);
echo "Decoded: " . $decoded . "\\n";
?>

Python

import urllib.parse

# URL encoding
text = "Hello World! Special chars: &?=/"
encoded = urllib.parse.quote(text)
print(f"Encoded: {encoded}")

# URL decoding
decoded = urllib.parse.unquote(encoded)
print(f"Decoded: {decoded}")

JavaScript

// URL encoding
const text = "Hello World! Special chars: &?=/";
const encoded = encodeURIComponent(text);
console.log("Encoded:", encoded);

// URL decoding
const decoded = decodeURIComponent(encoded);
console.log("Decoded:", decoded);

TypeScript

// URL encoding
const text: string = "Hello World! Special chars: &?=/";
const encoded: string = encodeURIComponent(text);
console.log("Encoded:", encoded);

// URL decoding
const decoded: string = decodeURIComponent(encoded);
console.log("Decoded:", decoded);

encodeURI 和 encodeURIComponent 有什麼區別?

encodeURI() 設計用於編碼完整的 URI,因此它不會編碼在 URL 中具有特殊意義的字符,例如 /、?、:、@、&、=、+、$ 和 #。 相比之下,encodeURIComponent() 會編碼所有特殊字符,使其適合用於編碼 URL 的部分,例如查詢字串參數。 在編碼查詢參數時,應始終使用 encodeURIComponent() 以確保所有特殊字符都被正確編碼。