1
1

More than 3 years have passed since last update.

URLをパースするJavascript

Last updated at Posted at 2021-02-22

URLのパースとは

URLの文字列を役割ごとに分解することです。例えば、
https://example.com/dir1/dir2/index.php?aaa=111/bbb&bbb=7#hello
というURLがあったとします。

前から順に、

部分 名称 説明
https:// プロトコル (スキームと呼ぶこともある) この例は Web上のリソースへ「SSLでアクセスする」ことを表しています。
example.com ホスト名、サーバー名 アクセス先のサーバーを指定しています
dir1/dir2/index.php パス(path、英語の「道、経路」) サーバーの中の、どのファイル(またはプログラム)にアクセスするか、その位置とファイル名を表しています。
aaa=111/bbb&bbb=7 クエリー プログラムに渡す情報(パラメーター)が、「?」の後に続きます。複数のパラメーターは「&」で区切ります。
hello ハッシュ ブラウザで表示処理する際の目印。ページ内リンクなどで利用されます。「#」の後に続きます。

もちろん、基本的にはすべて半角英数字です。

JavascriptでURLを分解するスクリプト


//元のURL
var url ="https://example.com/dir1/dir2/index.php?aaa=111/bbb&bbb=7#hello";

//分割して変数に格納します。
var protocol= url.split(':')[0];
var hash   = url.split('#')[1];
var query  = url.split('#')[0].split('?')[1];
var host   = url.split('#')[0].split('?')[0].split('/')[2];
var path   = url.split('#')[0].split('?')[0].replace(host,"").replace(/^https*:[\/]{3}/,"");

//ブラウザのコンソールに出力します
console.log( protocol ); // https
console.log( host ); // example.com
console.log( path ); // dir1/dir2/index.php
console.log( query ); // aaa=111/bbb&bbb=7
console.log( hash ); // hello

以上です。
PHPでは、parse_url という便利な関数がありますが、
それと似たような動きとなります。

1
1
3

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