日々プログラミング言語の勉強をしている京四郎のブログ -3ページ目

日々プログラミング言語の勉強をしている京四郎のブログ

日々プログラムの勉強をしている人がプログラム関係の記事を書くブログ

表示ページのファイル名を取得する方法

http://localhost/a001/001.html
から001.htmlを取得する方法。


function getNameFromURL(){
 return basename(location.href);
}


を使っていたが、location.hrefは、もし、ファイル名の後に、
?name=Johnとか#があっての取得してしまう。


http://localhost/a001/001.html?name=John
http://localhost/a001/001.html #


この問題はlocation.hrefでなくlocation.pathnameを使えば解決する。

l

ocation.href:URL全体を取得します
location.pathname:パスを取得します


function getNameFromURL(){
 return basename(location.pathname);
}


basename関数は次のものを使用してます。

JavaScript basename function
http://phpjs.org/functions/basename/  


function basename(path, suffix){
  // http://kevin.vanzonneveld.net
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net )
  // +   improved by: Ash Searle (http://hexmen.com/blog/ )
  // +   improved by: Lincoln Ramsay
  // +   improved by: djmix
  // *     example 1: basename('/www/site/home.htm', '.htm');
  // *     returns 1: 'home'
  // *     example 2: basename('ecra.php?p=1');
  // *     returns 2: 'ecra.php?p=1'
  var b = path.replace(/^.*[\/\\]/g, '');

  if (typeof(suffix) == 'string' && b.substr(b.length - suffix.length) == suffix) {
    b = b.substr(0, b.length - suffix.length);
  }

  return b;
}


表示ページのファイル名を取得する方法は他にもいろいろある。


[JavaScript] 表示ページのファイル名を取得する方法
http://b.0218.jp/20140404132553.html