JS 中的 URL 編碼(encode)與解碼(decode)方法

JS 中的 URL 編碼(encode)與解碼(decode)方法

Table of Contents

Toggle

1. encodeURIComponent2. decodeURIComponent3. encodeURI4. decodeURI使用場景區別

在 JavaScript 中,處理 URL 時經常需要進行編碼(encode)和解碼(decode)操作。以下是四個常用的方法介紹:

1. encodeURIComponent

encodeURIComponent 方法用於編碼 URI 的組件,這個方法會將 URI 組件中的特殊字符轉換為對應的 UTF-8 編碼序列。例如,將查詢字符串參數進行編碼時,這個方法非常適用。

const query = 'name=John Doe&age=23';

const encodedQuery = encodeURIComponent(query);

console.log(encodedQuery);

// 輸出: name%3DJohn%20Doe%26age%3D23

2. decodeURIComponent

decodeURIComponent 方法用於解碼先前由 encodeURIComponent 方法編碼的 URI 組件。它將已經編碼的字符序列轉換回原本的字符。

const encodedQuery = 'name%3DJohn%20Doe%26age%3D23';

const decodedQuery = decodeURIComponent(encodedQuery);

console.log(decodedQuery);

// 輸出: name=John Doe&age=23

如果你希望取得 URL 的資料可以避免出現亂碼(如空白、中文亂碼),你只需要在取得資料後,再進行一次 decodeURIComponent 就好

3. encodeURI

encodeURI 方法用於編碼整個 URI,而不是單個組件。這個方法只會編碼那些對 URI 有特別意義的字符,例如空格和一些標點符號,但不會編碼像 :, /, ?, #, & 等符號。

const uri = 'https://www.example.com/path name/';

const encodedURI = encodeURI(uri);

console.log(encodedURI);

// 輸出: https://www.example.com/path%20name/

4. decodeURI

decodeURI 方法用於解碼先前由 encodeURI 方法編碼的 URI。它將已經編碼的 URI 字符序列轉換回原本的字符。

const encodedURI = 'https://www.example.com/path%20name/';

const decodedURI = decodeURI(encodedURI);

console.log(decodedURI);

// 輸出: https://www.example.com/path name/

使用場景區別

使用 encodeURIComponent 和 decodeURIComponent 處理 URI 組件(如查詢字符串)。

使用 encodeURI 和 decodeURI 處理整個 URI。

這些方法在處理用戶輸入的數據或在應用程序中構建和解析 URL 時非常有用​ (MDN Web Docs)​​ (W3Schools.com)​​ (MDN Web Docs)​​ (Atta-Ur-Rehman Shah)​​ (W3Schools.com)​。

希望這篇文章能夠幫助你理解這些方法的使用及其區別。如需更多詳細資訊,可以參考 MDN Web Docs 和 W3Schools。

分享此文:

按一下即可分享至 X(在新視窗中開啟)

X

按一下以分享至 Facebook(在新視窗中開啟)

Facebook

分享到 LinkedIn(在新視窗中開啟)

LinkedIn

分享到 Tumblr(在新視窗中開啟)

Tumblr

分享到 Pinterest(在新視窗中開啟)

Pinterest

按一下以分享到 Telegram(在新視窗中開啟)

Telegram

更多

分享到 WhatsApp(在新視窗中開啟)

WhatsApp

請按讚:喜歡 正在載入...

相關文章

相关文章

世界杯什么时候开始,由哪些国家参加

bet体育365官网正规平台 06-27

盘点个性小众的国产车型,自主品牌们的创意性也不差

假的365不让提款怎么办 07-06

丝袜蛋(丝袜蛋)

假的365不让提款怎么办 07-15

模糊图片

假的365不让提款怎么办 07-19