반응형

backend에서 base64로 인코딩 된 스트링을 frontend에서 decode하여 사용하고자 한다.

 

이때 atob를 사용하면 끝날 것 같지만 실제로 그렇지 못하다.

 

그 이유는 atob는 유니코드를 디코딩 지원을 하지 않기 때문(btoa도 마찬가지)이다.

 

따라서 아래와 같이 unicode를 변환하는 utoa, atou 함수를 알아보자.

 

// base64 encoding using utf-8 character set
function utoa(str) {
    return window.btoa(unescape(encodeURIComponent(str)));
}
 // Parse the base64 string using the utf-8 character set 
function atou(str) {
    return decodeURIComponent(escape(window.atob(str)));
}

 

이제 atou를 호출하면 유니코드로 인코딩된 base64 데이터를 디코딩할 수 있다.

 

"5Lq6" 라는 데이터를 예시로 시작해보자.

 

 우선 atob를 이용하여 해당 내용을 디코딩하면 결과는 다음과 같다.

let s = "5Lq6"
atob(s)
"人"

 

해당 결과물을 유니코드로 변환해주는 escape를 사용하면 다음과 같아진다.

let s = "5Lq6"
atob(s)
"人"
escape("人")
"%E4%BA%BA"

 

여기서 decodeURIComponent를 이용하여 해당 내용을 decode해보면 결과물은 다음과 같다.

let s = "5Lq6"
atob(s)
"人"
escape("人")
"%E4%BA%BA"
decodeURIComponent("%E4%BA%BA")
"人"
decodeURI("%E4%BA%BA")
"人"

 

이와같이 유니코드 데이터를 디코딩하는 방법은 atou를 이용하면 쉽게 해결 할 수 있다.

https://www.programmersought.com/article/80171118269/

 

Js black magic use atob decoding utf-8 characters - Programmer Sought

Original address Reprint articles, invade The scene is like this, the background is passedbase64 The encoded string (the original string contains Chinese), needs to be decoded at the front end, but in jsatob Decoding method is not supportedunicode characte

www.programmersought.com

 

아래 내용은 decodeURI와 decodeURIComponent의 차이를 별첨해둔 내용이다.

The encodeURI function is intended for use on the full URI.
The encodeURIComponent function is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : @ & = + $ , #).

https://stackoverflow.com/questions/747641/what-is-the-difference-between-decodeuricomponent-and-decodeuri

 

What is the difference between decodeURIComponent and decodeURI?

What is the difference between the JavaScript functions decodeURIComponent and decodeURI?

stackoverflow.com

 

반응형