UrlEncode、UrlDecode、encodeURI、decodeURI、encodeURIComponent、decodeURIComponent
百分號編碼(Percent-encoding), 也稱作URL編碼(URL encoding)
URI所允許的字符分作保留與未保留。
Photo by wikipedia / CC BY-SA 3.0
URL 編碼的方法為,首先需要把該字符的ASCII的值表示為兩個16進位的數字,
然後在其前面放置轉義字符("%"),置入URI中的相應位置。
對於非ASCII字符, 則需先轉換為UTF-8 character sequence, 然後在每一個位元組其前面放置轉義字符("%")。
Photo by wikipedia / CC BY-SA 3.0
C#範例
using System;
using System.Web;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string UrlEncode = HttpUtility.UrlEncode("百");
string UTF8Encoding = "";
foreach (var item in Encoding.UTF8.GetBytes("百"))
{
UTF8Encoding += " " + item.ToString("x");
}
Console.WriteLine("UTF8Encoding = " + UTF8Encoding);
Console.WriteLine("UrlEncode = " + UrlEncode);
string UrlDecode = HttpUtility.UrlDecode(UrlEncode);
Console.WriteLine(UrlDecode);
Console.ReadKey();
}
}
}
結果為
javascript 範例
var url = "https://www.google.com.tw/百"; var a = encodeURI(url); var b = decodeURI(a);var c = encodeURIComponent(url);
var d = decodeURIComponent(c);
結果為
參考資料: