戻る

現在表示中のURLを取得
現在表示中のURLを取得

現在表示されているURLのホスト名を除くパスを取得する方法は
次のように取得します。
https://nekofes.github.io/android/index.html
ファイル名を含めたパスを取得します。
現在、表示中のURLが下記のパスと仮定します。
https://nekofes.github.io/android/index.html
これを「https://nekofes.github.io/android/index.html」で取得すると
android/index.html
の結果を取得できます。

URLの各情報を取得する方法は下記のようになります。
プロパティ名取得する結果(例)
location.href完全なURLhttps://nekofes.github.io/android/index.html?lang=0#section
location.protocolプロトコルhttps:
location.hostプロトコルhttps:
location.hostホスト名とポート番号localhost:8080
location.hostnameホスト名nekofes.github.io
location.portポート番号8080
location.pathnameパス名/android/index.html
location.searchクエリパラメータ(?から始まる部分)?lang=0
location.hashハッシュ(#から始まる部分)#section

[サンプル]
copy
function getPathName()
{
	return window.location.pathname;
}
function fileId()
{
	const pathname = getPathName();
	return pathname.split('/').pop();
}
function directoryPath()
{
	const pathname = getPathName();
	const lastSlashIndex = pathname.lastIndexOf('/');
	return pathname.substring(0, lastSlashIndex + 1);
}
console.log(getPathName());// /js/js94.html
console.log(fileId());// js94.html
console.log(directoryPath());// /js/

window.location.pathname
ファイル名を含めたパス全体を取得します。
このURLは下記のパスです。
https://nekofes.github.io/js/js94.html
この場合のパスの全体とは最初のスラッシュを含む
/js/js94.html
となります。

もしも、下記URLのようにディレクトリがない場合、下記の結果となります。
https://nekofes.github.io/index.html
実行した関数結果
getPathName()/index.html
fileId()index.html
directoryPath()/


戻る


著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。