JavaScript URIエンコード(encodeURIComponent)

目次

エンコードする(encodeURIComponent)

encodeURIComponent  ( 文字列 )
  • 文字列を渡すと、URIエンコードされた文字列が返ります。
  • 次の文字は変換しません 。 
    A-Z  a-z  0-9 - _ . ! ~ * ' ( )
  • URLの末尾にパラメータ(クエリ文字列)を付ける時にエンコードします。
    クエリ文字列の例:testform.php?text1=a&text2=b
    パラメータ(クエリ文字列)とは、URLの末尾に?が付き、「名前=値」の形式です。値が複数ある場合は「&」でつなげます。送信する文字列に?や=や&があるとフォーマットが壊れることや全角の文字等は送れないためエンコードします。
  • 注意点としてスラッシュ(/)やコロン(:)は変換されます。
    例えばhttp://example.comを変換した場合、://の部分も変換されてしまいます。

エンコードするサンプルです。

<script>

const str1 = 'あいAB1212';
console.log(encodeURIComponent(str1));
// %E3%81%82%E3%81%84AB12%EF%BC%91%EF%BC%92

const str2 = 'a1-_.!~*\'()?:#$&=';
console.log(encodeURIComponent(str2)); 
// a1-_.!~*'()%3F%3A%23%24%26%3D

</script>

8行目のアルファベット、10進数字、- _ . ! ~ * ' ( ) は、変換されていません。

元の文字列に戻す(decodeURIComponent)

decodeURIComponent ( encodeURIComponentでエンコードされた文字列 )
  • encodeURIComponent関数でエンコードされた文字列を元の文字列に戻します。

元の文字列に戻すサンプルです。

<script>

const str1 = "%E3%81%82%E3%81%84AB12%EF%BC%91%EF%BC%92";
console.log(decodeURIComponent(str1)); // あいAB1212

const str2 = "a1-_.!~*'()%3F%3A%23%24%26%3D";
console.log(decodeURIComponent(str2)); // a1-_.!~*'()?:#$&=

</script>

6行目のencodeURIComponent関数で変換されていない文字(a1-_.!~*'())は、そのまま出力されます。

関連の記事

JavaScript encodeURIComponentとencodeURIの違い

△上に戻る