紀錄工作經驗、相關知識,解決技術相關問題。

Javascript, React, 工作雜談, 新手 Jamp Holes, 未分類, 網站相關

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

在 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/

使用場景區別

  • 使用 encodeURIComponentdecodeURIComponent 處理 URI 組件(如查詢字符串)。
  • 使用 encodeURIdecodeURI 處理整個 URI。

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

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

7 留言

  1. Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://accounts.binance.com/bg/register?ref=YY80CKRN

  2. I am an investor of gate io, I have consulted a lot of information, I hope to upgrade my investment strategy with a new model. Your article creation ideas have given me a lot of inspiration, but I still have some doubts. I wonder if you can help me? Thanks.

  3. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://accounts.binance.com/ph/register-person?ref=OMM3XK51

  4. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  5. Your article helped me a lot, is there any more related content? Thanks!

  6. Reading your article helped me a lot and I agree with you. But I still have some doubts, can you clarify for me? I’ll keep an eye out for your answers.

  7. Cool. I spent a long time looking for relevant content and found that your article gave me new ideas, which is very helpful for my research. I think my thesis can be completed more smoothly. Thank you.

發表迴響