0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript encodeURIComponent()関数:URIコンポーネントのエンコード

0
Posted at

概念と使用方法

encodeURIComponent()関数はURLの特定の部分(例:検索キーワード、ファイル名、パラメータ値など)に使用される文字を安全にエンコードするために利用されます。
この関数はURL全体ではなく、クエリ文字列の値やキー、path segmentなどのURI Componentデータを安全にエンコードする際に有効です。

特徴

  • encodeURIComponent()関数は、URLにおいてプロトコル、ドメイン、パス区切り文字(/、:、?、&、#)など特別な意味を持つ文字もエンコードします。
  • ほとんどの特殊文字をエンコードするため、URI Component(例:クエリパラメータ値など)をエンコードする場合に有効です。
  • この関数は/、:、?、&、=などほとんどの特殊文字をエンコードするため、実際にURL構造を保持する必要がある場合、つまりURL全体をエンコードする用途には適していません。これらの文字はURLにおいてプロトコル、パス、クエリ、パラメータ区切りなどの構造を定義する重要な区切り記号であり、単なる文字ではなくURL文法の要素です。これらをすべてエンコードしてしまうと、ブラウザはその文字列をもはや有効なURLとして解釈できなくなります。(ただし「単なる文字列データとして保存」したり「送信用データとして利用」する場合には全く問題ありません。むしろそのような用途では安全にエンコードする手段となります。)

基本例

const uriComponent = "https://www.example.com/search?q=JavaScript & Web Development";
const encodedUriComponent = encodeURIComponent(uriComponent);

console.log(encodedUriComponent);
// 出力: "https%3A%2F%2Fwww.example.com%2Fsearch%3Fq%3DJavaScript%20%26%20Web%20Development"

構文

encodeURIComponent(uriComponent)

const searchQuery = "JavaScript & Web Development";
const page = 1;

const encodedQuery = encodeURIComponent(searchQuery);
const encodedPage = encodeURIComponent(page);

const baseUrl = "https://example.com/search";
const finalUrl = `${baseUrl}?q=${encodedQuery}&page=${encodedPage}`;

console.log(finalUrl);
// 出力: "https://example.com/search?q=JavaScript%20%26%20Web%20Development&page=1"

この例では、検索語 searchQuery とページ番号 page を URIコンポーネントと見なし、それぞれの値を encodeURIComponent() 関数でエンコードします。その後、この値を基に安全なURIを生成して出力します。このとき、& 記号や = 記号はURIのクエリ文字列で特別な意味を持つため、encodeURIComponent() 関数でエンコードされ、安全に使用されます。

参考資料

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?