溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》
  • 首頁 > 
  • 教程 > 
  • 開發技術 > 
  • js之encodeURI、encodeURIComponent、decodeURI、decodeURIComponent怎么用

js之encodeURI、encodeURIComponent、decodeURI、decodeURIComponent怎么用

發布時間:2023-04-17 10:01:55 來源:億速云 閱讀:412 作者:iii 欄目:開發技術

js之encodeURI、encodeURIComponent、decodeURI、decodeURIComponent怎么用

在JavaScript中,處理URL編碼和解碼是非常常見的操作。為了確保URL中的特殊字符能夠正確傳輸和解析,JavaScript提供了四個主要的函數:encodeURI、encodeURIComponent、decodeURIdecodeURIComponent。本文將詳細介紹這些函數的用法和區別。

1. encodeURI

encodeURI 函數用于對整個URI進行編碼。它會將URI中的特殊字符(如空格、中文等)轉換為UTF-8編碼的字符序列,但不會對URI中的保留字符(如:/?#[]@!$&'()*+,;=)進行編碼。

使用場景

  • 當你需要對整個URL進行編碼時,可以使用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"

2. encodeURIComponent

encodeURIComponent 函數用于對URI的組成部分進行編碼。與encodeURI不同,encodeURIComponent會對所有非字母數字字符進行編碼,包括保留字符。

使用場景

  • 當你需要對URL中的查詢參數或路徑部分進行編碼時,可以使用encodeURIComponent。

示例

const param = "name=張三&age=20";
const encodedParam = encodeURIComponent(param);
console.log(encodedParam);
// 輸出: "name%3D%E5%BC%A0%E4%B8%89%26age%3D20"

3. decodeURI

decodeURI 函數用于解碼由encodeURI編碼的URI。它會將編碼后的字符序列轉換回原始字符。

使用場景

  • 當你需要解碼整個URL時,可以使用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"

4. decodeURIComponent

decodeURIComponent 函數用于解碼由encodeURIComponent編碼的URI組成部分。它會將編碼后的字符序列轉換回原始字符。

使用場景

  • 當你需要解碼URL中的查詢參數或路徑部分時,可以使用decodeURIComponent。

示例

const encodedParam = "name%3D%E5%BC%A0%E4%B8%89%26age%3D20";
const decodedParam = decodeURIComponent(encodedParam);
console.log(decodedParam);
// 輸出: "name=張三&age=20"

總結

  • encodeURIdecodeURI 用于對整個URI進行編碼和解碼,保留URI中的保留字符。
  • encodeURIComponentdecodeURIComponent 用于對URI的組成部分進行編碼和解碼,編碼所有非字母數字字符。

在實際開發中,根據具體需求選擇合適的編碼和解碼函數,可以確保URL的正確傳輸和解析。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女