개발일지/TIL
TIL 23-06-28 javascript decodeURIComponent
sdoram
2023. 6. 28. 23:48
1. javascript decodeURIComponent
문제점
js url 사용 중 img url을 제대로 읽지 못하는 이슈 발생

시도해 본 것들
exhibitionImg.setAttribute("onerror", "this.src='/static/img/default-img.jpg'")
if (exhibition.image) {
if (exhibition.image.includes('https:')) {
exhibitionImg.setAttribute("src", exhibition.image);
} else if (exhibition.image.includes('https%3A')) {
// 대체 url 코드로 인코딩된 url 디코딩 하기
exhibitionImg.setAttribute("src", decodeURIComponent(exhibition.image.split("media/")[1]));
} else if (exhibition.image.includes('media')) {
exhibitionImg.setAttribute("src", `${backendBaseURL.split('/api')[0]}${exhibition.image}`)
}
} else {
exhibitionImg.setAttribute("src", "/static/img/default-img.jpg")
}
해결 방법
exhibitionImg.setAttribute("onerror", "src='/static/img/default-img.jpg'")
if (exhibition.image) {
if (exhibition.image.includes('https%3A')) {
// 대체 url 코드로 인코딩된 url 디코딩 하기
exhibitionImg.setAttribute("src", `https://${decodeURIComponent(exhibition.image.split("https%3A")[1])}`)
}
else if (exhibition.image.includes('https:')) {
exhibitionImg.setAttribute("src", exhibition.image)
} else {
exhibitionImg.setAttribute("src", `${backendBaseURL.split('/api')[0]}${exhibition.image}`)
}
어설프지만 https:를 직접 적어주고 :의 대체url인 %3A을 기준으로 split하기
알게 된 점
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
escape는 과거에 사용되다가 사장된 함수이다.
encodeURI는 아스키 코드중 :, ;, /, =, ?, &을 제외하고 인코딩하는 경우 사용
decodeURIComponent는 :, ;, /, =, ?, &과 아스키 코드가 아닌 한글 등도 모두 인코딩 가능하다