在JavaScript中,處理URL編碼和解碼是非常常見的操作。為了確保URL中的特殊字符能夠正確傳輸和解析,JavaScript提供了四個主要的函數:encodeURI
、encodeURIComponent
、decodeURI
和 decodeURIComponent
。本文將詳細介紹這些函數的用法和區別。
encodeURI
函數用于對整個URI進行編碼。它會將URI中的特殊字符(如空格、中文等)轉換為UTF-8編碼的字符序列,但不會對URI中的保留字符(如:/?#[]@!$&'()*+,;=
)進行編碼。
encodeURI
。const url = "https://example.com/路徑/文件.html?name=張三&age=20";
const encodedUrl = encodeURI(url);
console.log(encodedUrl);
// 輸出: "https://example.com/%E8%B7%AF%E5%BE%84/%E6%96%87%E4%BB%B6.html?name=%E5%BC%A0%E4%B8%89&age=20"
encodeURIComponent
函數用于對URI的組成部分進行編碼。與encodeURI
不同,encodeURIComponent
會對所有非字母數字字符進行編碼,包括保留字符。
encodeURIComponent
。const param = "name=張三&age=20";
const encodedParam = encodeURIComponent(param);
console.log(encodedParam);
// 輸出: "name%3D%E5%BC%A0%E4%B8%89%26age%3D20"
decodeURI
函數用于解碼由encodeURI
編碼的URI。它會將編碼后的字符序列轉換回原始字符。
decodeURI
。const encodedUrl = "https://example.com/%E8%B7%AF%E5%BE%84/%E6%96%87%E4%BB%B6.html?name=%E5%BC%A0%E4%B8%89&age=20";
const decodedUrl = decodeURI(encodedUrl);
console.log(decodedUrl);
// 輸出: "https://example.com/路徑/文件.html?name=張三&age=20"
decodeURIComponent
函數用于解碼由encodeURIComponent
編碼的URI組成部分。它會將編碼后的字符序列轉換回原始字符。
decodeURIComponent
。const encodedParam = "name%3D%E5%BC%A0%E4%B8%89%26age%3D20";
const decodedParam = decodeURIComponent(encodedParam);
console.log(decodedParam);
// 輸出: "name=張三&age=20"
encodeURI
和 decodeURI
用于對整個URI進行編碼和解碼,保留URI中的保留字符。encodeURIComponent
和 decodeURIComponent
用于對URI的組成部分進行編碼和解碼,編碼所有非字母數字字符。在實際開發中,根據具體需求選擇合適的編碼和解碼函數,可以確保URL的正確傳輸和解析。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。