encodeURIComponent()와 encodeURI()의 차이

장동균·2022년 2월 24일
0

https://www.freecodecamp.org/news/javascript-url-encode-example-how-to-use-encodeuricomponent-and-encodeuri/
해당 글에 대한 번역입니다.

URL에는 아스키 코드로 정의된 128개의 문자들만이 사용 가능하다. 때문에 128개 이외의 문자들이 URL로 오기 위해서는 반드시 인코딩되어야 한다.

128개의 아스키 코드 중에서도 특별한 기능을 하는 &, space, !와 같은 문자들은 url로 입력되기 전에 escaped 되어야 한다. 그렇지 않으면 우리가 예측하지 못한 에러가 발생할 수 있다.


encodeURI()encodeURIComponent()의 차이는 무엇일까?

  1. encodeURI()~!@#$&*()=:/,;?+를 인코딩하지 않는다. 반면 encodeURIComponent()~!*()를 인코딩하지 않는다.

    const url = 'https://www.twitter.com'
    console.log(encodeURI(url))             //https://www.twitter.com
    console.log(encodeURIComponent(url))   	//https%3A%2F%2Fwww.twitter.com
  2. encodeURIComponent()는 URL의 일부분을 인코딩해야할 때 사용한다. 반면 encodeURI()는 URL 전체를 인코딩해야할 때 사용한다.


언제 인코딩 해야할까?

  1. input으로 받은 문자열을 그대로 URL에 사용해야 하는데, 띄어쓰기가 있을 수 있는 경우

    encodeURI("http://www.mysite.com/a file with spaces.html") 
    //http://www.mysite.com/a%20file%20with%20spaces.html
  2. 쿼리 스트링의 파라미터 값을 넣어줘야 할 때

    let param = encodeURIComponent('mango')
     let url = "http://mysite.com/?search=" + param + "&length=99"; //http://mysite.com/?search=mango&length=99
  3. 특별한 용도로 예약되어 있는 문자를 URL에 사용해야 할 때 (ex. URL 스킴의 구분자들)

    let params = encodeURIComponent('mango & pineapple')
     let url = "http://mysite.com/?search=" + params; //http://mysite.com/?search=mango%20%26%20pineapple

결론

완벽한 URL을 인코딩 해야 한다면 encodeURI()를, URL의 일부분을 인코딩해야 한다면 encodeURIComponent()를 사용하자!

profile
프론트 개발자가 되고 싶어요

0개의 댓글