最后一段网址

问题描述 投票:191回答:23

如何获取网址的最后一段?我有以下脚本显示单击的锚标记的完整URL:

$(".tag_name_goes_here").live('click', function(event)
{
    event.preventDefault();  
    alert($(this).attr("href"));
});

如果网址是

http://mywebsite/folder/file

我如何才能让它在警告框中显示网址的“文件”部分?

javascript jquery
23个回答
308
投票

您还可以使用lastIndexOf()函数查找URL中最后一次出现的/字符,然后使用substring()函数返回从该位置开始的子字符串:

console.log(this.href.substring(this.href.lastIndexOf('/') + 1));

这样,你就可以避免创建一个包含所有网段的数组,就像split()那样。


4
投票

仅使用javascript建立Frédéric的答案:

var url = document.URL

window.alert(url.substr(url.lastIndexOf('/') + 1));

3
投票

也,

var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);

3
投票

如果你不担心使用拆分生成额外的元素,那么过滤器可以处理你提到的尾部斜杠的问题(假设你有浏览器支持过滤器)。

url.split('/').filter(function (s) { return !!s }).pop()

3
投票
// Store original location in loc like: http://test.com/one/ (ending slash)
var loc = location.href; 
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

targetValue = 1

如果您的网址如下:

http://test.com/one/

要么

http://test.com/one

要么

http://test.com/one/index.htm

然后loc最终看起来像:http://test.com/one

现在,由于您需要最后一项,请运行下一步以加载您最初想要的值(targetValue)。

var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

3
投票
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));

使用本机pathname属性,因为它最简单,并且已被浏览器解析和解析。 $(this).attr("href")可以返回像../..这样的值,这些值不会给你正确的结果。

如果你需要保留searchhash(例如来自foo?bar#bazhttp://quux.com/path/to/foo?bar#baz),请使用:

window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);

2
投票
var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL

复制自this answer


2
投票

要获取当前窗口的最后一部分:

window.location.href.substr(window.location.href.lastIndexOf('/') +1)


2
投票

无论尾部斜杠如何,都返回最后一个段:

var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();

console.log(val);

1
投票

更新了raddevus答案:

var loc = window.location.href;
loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);

将url的最后一个路径打印为字符串:

test.com/path-name = path-name

test.com/path-name/ = path-name

1
投票

你可以先删除,如果有/在最后,然后获取网址的最后一部分

let locationLastPart = window.location.pathname
if (locationLastPart.substring(locationLastPart.length-1) == "/") {
  locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
}
locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);

129
投票

var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash

console.log(lastSegment);

0
投票

我相信在执行子字符串之前删除尾部斜杠('/')会更安全。因为我的场景中有一个空字符串。

window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));

0
投票

我正在使用正则表达式和拆分:

var last_path = location.href.match(/./(。[\ w])/)[1] .split(“#”)[0] .split(“?”)[0]

最终会忽略#? &/结束网址,这发生了很多。例:

https://cardsrealm.com/profile/cardsRealm - >返回cardsRealm

https://cardsrealm.com/profile/cardsRealm#hello - >返回cardsRealm

https://cardsrealm.com/profile/cardsRealm?hello - >返回cardsRealm

https://cardsrealm.com/profile/cardsRealm/ - >返回cardsRealm


0
投票

我真的不知道正则表达式是否是解决此问题的正确方法,因为它可以真正影响代码的效率,但是下面的正则表达式将帮助您获取最后一个段,它仍然会给你最后一个段,即使URL之后是一个空的/。我想出的正则表达式是:

[^\/]+[\/]?$

0
投票
// https://x.com/boo/?q=foo&s=bar = boo
// https://x.com/boo?q=foo&s=bar = boo
// https://x.com/boo/ = boo
// https://x.com/boo = boo

const segment = new 
URL(window.location.href).pathname.split('/').filter(Boolean).pop();
console.log(segment);

适合我。


52
投票
window.location.pathname.split("/").pop()

25
投票

只是另一种正则表达式的解决方案。

var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);

16
投票

Javascript具有与字符串对象相关联的函数split,可以帮助您:

var url = "http://mywebsite/folder/file";
var array = url.split('/');

var lastsegment = array[array.length-1];

9
投票

或者您可以使用正则表达式:

alert(href.replace(/.*\//, ''));

9
投票

如果路径很简单,其他答案可能有效,只包含简单的路径元素。但是当它包含查询参数时,它们就会中断。

更好地使用URL对象来获得更强大的解决方案。它是对当前URL的解析解释:

输入:const href = 'https://stackoverflow.com/boo?q=foo&s=bar'

const last = new URL(href).pathname.split('/').pop();
console.log(last);

输出:'boo'

这适用于所有常见浏览器。只有我们垂死的IE不支持(也不会)。对于IE,有一个polyfills可用(但如果你care)。


8
投票
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);

5
投票

我知道,为时已晚,但对于其他人:我强烈建议使用PURL jquery plugin。 PURL的动机是url也可以用'#'来分段(例如:angular.js链接),即url看起来像

    http://test.com/#/about/us/

要么

    http://test.com/#sky=blue&grass=green

使用PURL,您可以轻松决定(细分/细分)您想要获得的细分。

对于“经典”的最后一段你可以写:

    var url = $.url('http://test.com/dir/index.html?key=value');
    var lastSegment = url.segment().pop(); // index.html
© www.soinside.com 2019 - 2024. All rights reserved.