LoginSignup
36
17

More than 3 years have passed since last update.

JavaScriptにおける正しいURLエンコードの方法(encodeURIとencodeURIComponentの違い)

Last updated at Posted at 2020-06-10

はじめに

javascriptにおいてURLをパーセントエンコードする場合に使用するencodeURIencodeURIComponentの違いを説明します。

URLエンコードとは

URLに含まれる日本語とか半角スペースとかを「あ」→「%E3%81%82」、「 」→「%20」に変換すること

URLデコードとは

エンコードされたURLを元に戻すこと

javascriptでやってみる

let url = "http://api/user/太郎?age=20";
console.log(encodeURI(url));
console.log(encodeURIComponent(url));
実行結果
http://api/user/%E5%A4%AA%E9%83%8E?age=20
http%3A%2F%2Fapi%2Fuser%2F%E5%A4%AA%E9%83%8E%3Fage%3D20

encodeURIComponentはURLの形式としておかしな文字列になってしまいました。

違い

URL内で特別な意味を持つ「; , / ? : @ & = + $ #」の扱いが違います。

  • encodeURI
    エンコードされない
  • encodeURIComponent
    エンコードされる

ですので、URL全体をエンコードする場合はencodeURIで、パラメータなどの部分的な文字列をエンコードする場合はencodeURIComponentを使用しましょう。

ありそうな失敗

例えばhttp://api/user?name=XXXのXXX部分にユーザ名「山田=太郎」を指定する場合

  1. ユーザ名を設定したURLを作成する
    http://api/user?name=山田=太郎
  2. encodeURIする
    http://api/user?name=%E5%B1%B1%E7%94%B0=%E5%A4%AA%E9%83%8E
  3. 受け取った側がdecodeURIする
    http://api/user?name=山田=太郎
  4. パラメータを分割して取得する
    "?"以降をパラメータとして認識し、それを"&"で分割し、"="で分割して、キーと値を取得する。
    その場合、「キー:name」、「値:山田」となる

正しいやり方

  1. ユーザ名をencodeURIComponentする %E5%B1%B1%E7%94%B0%3D%E5%A4%AA%E9%83%8E
  2. エンコードしたユーザ名を設定したURLを作成する
    http://api/user?name=%E5%B1%B1%E7%94%B0%3D%E5%A4%AA%E9%83%8E
  3. 受け取った側がパラメータを分割して取得する
    "?"以降をパラメータとして認識し、それを"&"で分割し、"="で分割して、キーと値を取得する。
    その場合、「キー:name」、「値:%E5%B1%B1%E7%94%B0%3D%E5%A4%AA%E9%83%8E」となる
  4. decodeURIComponentする
    「キー:name」、「値:山田=太郎」が取得できる
36
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
17