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

Javascript

Javascript encode decode

簡單說明常用 Javascript encode(編碼) 、decode(解碼) 使用方法與注意事項

encodeURI

encodeURI 會將所有字符全部進行編碼,但少數符號字符將不被轉義,因此特性,所以不適合用於 URL 的處理(POST , GET)。

類型包含
保留字符; , / ? : @ & = + $
非轉義字符字母(A-Za-z) 數字(0-9),以及符號-_.!~*'()
視為數字符號#
encodeURI 編碼 – 不轉義字符

Example:

console.log(encodeURI('abc~! _'))
// 'abc~!%20_'
console.log(encodeURI('@#$%^&'))
// '@#$%25%5E&'
console.log(encodeURI('+-*/'))
// '+-*/'
console.log(encodeURI('()|\\"\''))
// "()%7C%5C%22'"

decodeURI

decodeURI 會將所有字符全部進行編碼,不適合用於頁面 URL 的處理,用法如下:

console.log(decodeURI('abc~!%20_'))
// 'abc~! _'
console.log(decodeURI('@#$%25%5E&'))
// '@#$%^&'
console.log(decodeURI('+-*/'))
// '+-*/'
console.log(decodeURI("()%7C%5C%22'"))
// `()|\\"'`

encodeURIComponent()

類型包含
保留字符~!*()’
非轉義字符字母(A-Za-z) 數字(0-9)
encodeURI 編碼 – 不轉義字符

encodeURIComponent() 會將字串轉換為 UTF-8 編碼字元,適合用於POST、GET的參數以及一般URL的編碼,可避免字符在轉義後,遭不正確中斷問題。

var c = 'ddd&eee'
var url = 'domain.com/a&b?c=' + c + '&f=ggg'
// 得到URL : domain.com/a&b?c=ddd&eee&f=ggg

上面範例我們可以看到,我們希望得到一個帶有GET c = ddd&eee 與 f=ggg 的URL,一般情不轉義況下直接組合,實際上會得到c = ddd , eee , f=ggg 三筆GET資料。

而這裡如果使用 encodeURI 來進行編碼,也不會得到正確的結果,因為符號&是encodeURI 的保留字符,所以並不會進行處理,如下:

var c = encodeURI('ddd&eee')
// c = 'ddd&eee'

所以在處理URL 時,通常會針對參數,使用 encodeURIComponent 進行編碼處理,這樣就可以完整正確地將URL,如下:

var c = encodeURIComponent('ddd&eee')
// c = 'ddd%26eee'
var url = 'domain.com/a&b?c=' + c + '&f=ggg'
// 得到URL : domain.com/a&b?c=ddd%26eee&f=ggg

decodeURIComponent()

用於對 encodeURIComponent()編碼過的資料進行解碼,如下:

var c = encodeURIComponent('ddd&eee')
// c = 'ddd%26eee'
var url = 'domain.com/a&b?c=' + c + '&f=ggg'
// 'domain.com/a&b?c=ddd&eee&f=ggg'

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.

發表迴響