當你需要處理某些特定字元以避免錯誤,可以將相關的字串進行編碼,JavaScript 內建了 encodeURIComponent() 與 decodeURIComponent() 以支援相關的操作,考慮以下的程式片段:
x 變數所儲存的字串包含了逗號、空白與分號,接下來調用 encodeURIComponent() 對其進行編碼,得到編碼後的結果,並儲存於 encode_x ,接下來再將其結果值傳入 decodeURIComponent() ,得到解碼後的結果 decode_x ,最後分別將這兩個值輸出。內容如下:
abc%2C%20xyz%3B123%20
abc, xyz;123
如你所見, encodeURIComponent() 將其中的逗號、空白與分號進行編碼,而decodeURIComponent() 則進行解碼還原。
字串的編碼與解碼常見於網址字串的轉換,或是將資料儲存至 cookie 的場合,儲存空白或逗號這一類的字元在相關狀況下都會出問題,因此必須先經由 encodeURIComponent() 編碼,它主要針對 , / ? : @ & = + $ # 這幾個字元進行編碼,再透過 decodeURIComponent() 解碼。
<script>
var x = 'abc, xyz;123 ';
var encode_x = encodeURIComponent(x);
var decode_x = decodeURIComponent(encode_x);
console.log(encode_x);
console.log(decode_x);
</script>
x 變數所儲存的字串包含了逗號、空白與分號,接下來調用 encodeURIComponent() 對其進行編碼,得到編碼後的結果,並儲存於 encode_x ,接下來再將其結果值傳入 decodeURIComponent() ,得到解碼後的結果 decode_x ,最後分別將這兩個值輸出。內容如下:
abc%2C%20xyz%3B123%20
abc, xyz;123
如你所見, encodeURIComponent() 將其中的逗號、空白與分號進行編碼,而decodeURIComponent() 則進行解碼還原。
字串的編碼與解碼常見於網址字串的轉換,或是將資料儲存至 cookie 的場合,儲存空白或逗號這一類的字元在相關狀況下都會出問題,因此必須先經由 encodeURIComponent() 編碼,它主要針對 , / ? : @ & = + $ # 這幾個字元進行編碼,再透過 decodeURIComponent() 解碼。
沒有留言:
張貼留言