LoginSignup
0
0

More than 1 year has passed since last update.

JavaScript クエリパラメータをエスケープ処理

Posted at

はじめに

クエリパラメータに、扱えないマルチバイト文字などが含まれる可能性がある場合は、
表記可能な文字列に変換するエスケープ処理が必要です。このような変換処理を「URIエンコード」と言います
方法は主に三つ。

encodeURI()

URIの予約文字以外の記号をエンコードするグローバル関数
decodeURI()で元の文字列に戻せます。

エスケープされないもの:

A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

var set1 = ";,/?:@&=+$#"; // 予約文字
var set2 = "-_.!~*'()";   // 予約されていない記号
var set3 = "ABC abc 123"; // 英数字 + 空白

console.log(encodeURI(set1)); // ;,/?:@&=+$#
console.log(encodeURI(set2)); // -_.!~*'()
console.log(encodeURI(set3)); // ABC%20abc%20123 (空白は %20 にエンコードされる)

encodeURIComponent()

encodeURI()に加え、HTTPのGET,POSTリクエストでの特別な文字もエスケープするようにしたグローバル関数
decodeURIComponent()で元に戻せます。

エスケープされないもの:

A-Z a-z 0-9 - _ . ! ~ * ' ( )

var set1 = ";,/?:@&=+$#"; // 予約文字
var set2 = "-_.!~*'()";   // 予約されていない記号
var set3 = "ABC abc 123"; // 英数字 + 空白

console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23
console.log(encodeURIComponent(set2)); // -_.!~*'()
console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (空白は %20 にエンコードされる)

escape()

非推奨。Web標準から削除された。使用しているプラットフォームやブラウザーで得られる結果が異なる。特別な理由がない限り使わない。

参考

JavaScript 本格入門 - 山田 祥寛

0
0
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
0
0