JavascriptでURLを取得するサンプルです。URLの一部であるプロトコル、ホスト名、ファイル名、パラーメーターを取得するには、取得したURLを元に正規表現で目的の部分を抽出するか、URLの不必要な部分を削除します。URLの一部取得方法については、様々な記載方法があるので使いやすい書き方をするのがよいと思います。
URL部分取得サンプル
alertはデータの出力をしているだけです。取得データが配列の場合は、rs[1]の様な記述をしています。
・URL全体
rs = window.location.href;
alert(rs);
・プロトコル
rs = window.location.protocol;
alert(rs);
・ホスト名
rs = window.location.host;
alert(rs);
・ルートパス
rs = window.location.href.replace(/\\/g, ‘/’).replace(/^[^/]*\/\/[^/]*/, ”);
alert(rs);
・デレクトリ
rp = window.location.href.replace(/\\/g, ‘/’).replace(/\/[^/]*$/, ”);
if(rp){
protocol = window.location.protocol;
hostname = window.location.host;
rp = rp.replace(protocol+”//”+hostname,”");
}
alert(rp);
・ファイル名
ファイル名は拡張子有りです。
rs = window.location.href.replace(/\\/g, ‘/’).replace(/.*\//, ”).replace(/\?.*$/, ”);
alert(rs);
・拡張子
fname = window.location.href.replace(/\\/g, ‘/’).replace(/.*\//, ”).replace(/\?.*$/, ”);
if(fname){
rs = fname.split(“.”);
}
alert(rs[1]);
・パラメーター
rs = window.location.href.match(/\?([^?]*)$/);
alert(rs[1]);
・パラメーター(配列)
取得するデータは配列です。パラメータ名を配列のキー名にしています。
function getRequest(){
if(location.search.length > 1) {
var get = new Object();
var ret = location.search.substr(1).split(“&”);
for(var i = 0; i < ret.length; i++) {
var r = ret[i].split(",");
var rt = r[0].split("=");
get[rt[0]] = rt[1];
}
return get;
} else {
return false;
}
};
rs = getRequest();
alert(rs['name']);
(注意)
上記で記載している方法について、URLの有無、URL以外のデータの場合の条件分岐を記載していません。もし、お使いになる場合は注意してください。
(感想 )
久しぶりのJavascriptで、URLの取得方法を完全に忘れていました。次回も忘れているので、覚書として記載します。