jquery - JavaScriptでURLの最後のセグメント
URLの最後のセグメントを取得するにはどうすればいいですか?次のスクリプトは、クリックされたアンカータグの完全なURLを表示します:
$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});
もしそのURLが
http://mywebsite/folder/file
アラートボックスにURLの「file」の部分だけを表示するにはどうすればいいですか?
回答 #1
また、lastIndexOf() 関数を使用して URL 内の / 文字の最後の出現位置を見つけ、次に substring() 関数を使用してその位置から始まる部分文字列を返すこともできます:
console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
そうすることで、split() が行うように、すべてのURLセグメントを含む配列を作成することを避けられます。
回答 #2
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);回答 #3
window.location.pathname.split("/").pop()
回答 #4
パスが単純で、単純なパス要素だけで構成されている場合は、他の回答も機能するかもしれません。しかし、クエリパラメータが含まれると、それらは壊れます。
より堅牢な解決策を得るために、代わりにこれには URL オブジェクトを使用する方が良いです。これは現在の URL の解析された解釈です:
入力: const href='https://stackoverflow.com/boo?q=foo&s=bar'
const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);
出力:「ブー」
これはすべての一般的なブラウザで動作します。私たちの衰退しつつあるIEだけがそれをサポートしておらず(そしてサポートもしません)。ただし、IE用にはポリフィルが利用可能です(もし気にするなら)。
回答 #5
正規表現を使ったもう一つの解決策。
var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
回答 #6
JavaScript には、文字列オブジェクトに関連付けられた split 関数があり、次のことを助けることができます:
const url = "http://mywebsite/folder/file";
const array = url.split('/');
const lastsegment = array[array.length-1];
回答 #7
split()、filter()、pop() を使って URL の最後のセグメントを取得する最短の方法
function getLastUrlSegment(url) {
return new URL(url).pathname.split('/').filter(Boolean).pop();
}
console.log(getLastUrlSegment(window.location.href));
console.log(getLastUrlSegment('https://x.com/boo'));
console.log(getLastUrlSegment('https://x.com/boo/'));
console.log(getLastUrlSegment('https://x.com/boo?q=foo&s=bar=aaa'));
console.log(getLastUrlSegment('https://x.com/boo?q=foo#this'));
console.log(getLastUrlSegment('https://x.com/last segment with spaces'));私にはうまくいきます。
回答 #8
または正規表現を使用することもできます:
alert(href.replace(/.*\//, ''));
