카테고리 없음

javascript url을 디코딩하여 %20을 공백으로 되돌리기

Neda 2023. 10. 22. 00:08

javascript url을 디코딩하여 %20을 공백으로 되돌리기

브라우저는 ASCII 문자들을 사용하여 URL을 사용하는데, 예외적으로 ASCII 문자가 아닌 문자들이 포함되어 있을 때가 있다. 이럴 때 브라우저는 비 ASCII 문자들을 적절하게 ASCII 문자 형식으로 변환하여 사용한다. 또한 URL에는 공백이 사용될 수 없다.

 

Nextjs params는 인코딩된 값

Nextjs에서는 params 값을 인코딩된 그대로 내보낸다.

예를 들면 사용자는 'iron man'을 검색했지만 api 호출을 받은 서버는 'iron%2520man'이라는 요청을 받게 된다.

  1. 여기서 공백은 사용자가 'iron man'을 검색하여 'search/iron man' 페이지로 이동할 때
    ' ' => '%20' 으로 변환된다.
  2. 그리고 params에서 이 값인 'iron%20man'을 받아와서 rest api get 호출에 그대로 사용하면 '%20'에서 '%'는 '%25'로 변경되고 api 호출 주소는 아래와 같이 두 번 인코딩 된 값이 되어 버린다.
api/v1/public/characters?nameStartsWith=iron%2520man
// /app/search/[name]/page.tsx
// ❌
const SearchPage = async ({ params: { name } }: Props) => {
  const results = await getCharactersByName(name)
  ...
 }

 

decodeURIComponent()를 사용하여 디코딩

자바스크립트에서는 이렇게 인코딩 된 URI를 디코딩 해주는 간편한 함수를 제공한다.

(물론 인코딩하는 함수도 제공한다.)

decodeURIComponent 함수에 인코딩된 URI를 전달하면 디코딩된 본래의 문자열을 확인할 수 있다.

// /app/search/[name]/page.tsx
// ❌
const SearchPage = async ({ params: { name } }: Props) => {
  const decodedName = decodeURIComponent(name)
  const results = await getCharactersByName(decodedName)
  ...
 }

 

 

 

 

HTML URL Encoding Reference

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com


 

 

decodeURIComponent() - JavaScript | MDN

The decodeURIComponent() function decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent() or by a similar routine.

developer.mozilla.org