URL的最后一段


228

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

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

如果网址是

http://mywebsite/folder/file

如何只在警报框中显示网址的“文件”部分?


以下是我正在工作的Java脚本解决方案,希望能有所帮助。stackoverflow.com/a/38370175/610951
Ravi Shankar Kota

Answers:


369

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

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

这样,您就可以避免创建包含所有URL段的数组split()


3
@oshirowanen,不,但是它将从每个URL段创建一个数组元素。由于您仅对最后一段感兴趣,因此分配许多您永远不会使用的数组元素可能会很浪费。
弗雷德里克·哈米迪

11
但是,如果url变得像admin/store/tour/-1/这样,它将是''字符串吗?
2014年

1
@Set,也许更好,肯定会慢一些。
弗雷德里克·哈米迪

1
如果该网址/末尾包含怎么办?
Sнаđошƒаӽ

6
Attn:@Set Kyar Wa Lar Aug和@Sнаđошƒаӽ解决方案的URL /末尾包含:var url = window.location.href.replace(/\/$/, ''); /* remove optional end / */ var lastSeg = url.substr(url.lastIndexOf('/') + 1);
Ross

151

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

console.log(lastSegment);


您能解释一下它是如何工作的吗?据我所知.pop()用于删除数组的最后一个元素。但在这里它显示了我网址的最后一个元素!
激发Shahin

1
Split会将您的网址转换为一个数组,该数组采用网址的每个部分(以/分隔)。因此,最后一个段是url和随后创建的数组的最后一个元素。
stephen,2016年

10
如果网址以“ /”结尾,则无法使用,即http://mywebsite/folder/file/
Peter Ludlow

@PeterLudlow它可在Chrome 76中运行,请您详细说明
一下-zyrup

1
@PeterLudlow之所以起作用,是因为在JS摘要"" == false中,空字符串是假的,在这种情况下,它将用空字符串弹出数组的一部分
zyrup

85
window.location.pathname.split("/").pop()

2
简单容易。谢谢。
krezaeim '18

3
完美,整洁,很棒
Babak Habibi '18

1
漂亮干净的回应
Zarkys Salas

1
这正是我想要的。我发现使用react-router-dom是最干净的解决方案,它找到URL的最后一部分跟在最后一个正斜杠之后/console.log(history.location.pathname.split("/").pop()) 如果有更好的方法,我想知道!希望此评论可以引导更多的人来回答您。感谢@ Dblock247
Tralawar

旁注:如果URL确实设置了查询参数(例如.../file?var=value&foo=bar),则此方法不起作用。此解决方案以更健壮和更现代的方式解决了该问题:stackoverflow.com/a/51795122/1123743
塞巴斯蒂安·巴特

30

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

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

我喜欢它谢谢:)。
Salil Sharma

18

Javascript具有与字符串对象相关联的功能拆分,可以帮助您:

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

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

17

如果路径很简单(仅由简单路径元素组成),则其他答案可能会起作用。但是,当它还包含查询参数时,它们就会中断。

更好地使用网址为此对象,以获得更可靠的解决方案。它是对当前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);

输出: 'boo'

这适用于所有常见的浏览器。只有我们垂死的IE不支持(并且不会)。对于IE,有一个polyfills可用(如果您很在意的话)。



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

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

如果您不担心使用split生成额外的元素,则filter可以解决您提到的斜杠问题(假设您对filter拥有浏览器支持)。

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);

我可能会错过一些东西,但是在“ test.com/one ”中,loc最终看起来像是“ test.com ”。我认为应该像这样:if(loc.lastIndexOf('/')==(loc.length -1)){loc = loc.substr(0,loc.length-1)} else {var isFile = loc。 substr(loc.lastIndexOf('/'),loc.length).indexOf('。')!= -1; if(isFile)loc = loc.substr(0,loc.lastIndexOf('/')); }
艾伦·拉昆

如果斜线为search或,则失败hash
沃尔夫

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

使用本机pathname属性,因为它最简单,并且已经由浏览器解析和解析。$(this).attr("href")可以返回类似的值../..无法获得正确结果的值。

如果您需要保留searchand hash(例如foo?bar#bazfrom http://quux.com/path/to/foo?bar#baz),请使用以下命令:

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

还希望添加该功能以pathname除去查询参数,但href不要这样做。
Max Heiber

3

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

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


3

您可以先删除结尾是否有/,然后获取网址的最后一部分

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

3

返回最后一个段,而不管后面是否有斜杠:

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

console.log(val);


您可能不希望使用path.sep文字斜杠。请参阅nodejs.org/api/path.html#path_path_sep。这将使您的代码可跨操作系统移植。
亚伦

1
不错的主意,但是它将不再在浏览器中起作用
John Doherty

好点子。我应该说这在命令行脚本/服务器端nodejs中是首选的。
亚伦


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

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);

为我工作。


0

我知道它很旧,但是如果您想从URL中获取它,则可以简单地使用:

document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);

document.location.pathname从当前URL获取路径名。 lastIndexOf获取以下正则表达式最后一次出现的索引,在我们的例子中为/.。点表示任何字符,因此,如果/URL上的最后一个字符,则该点将不计算在内。 substring将在两个索引之间剪切字符串。


0

如果网址是 http://localhost/madukaonline/shop.php?shop=79

console.log(location.search); 将要带来 ?shop=79

所以最简单的方法是使用location.search

您可以在此处此处查找更多信息


0

您可以使用简单路径(w / 0)查询字符串等执行此操作。

虽然可能过于复杂,但可能没有表现,但我想以此reduce为乐。

  "/foo/bar/"
    .split(path.sep)
    .filter(x => x !== "")
    .reduce((_, part, i, arr) => {
      if (i == arr.length - 1) return part;
    }, "");
  1. 在路径分隔符上分割字符串。
  2. 过滤掉空的字符串路径部分(路径中的斜杠可能会发生这种情况)。
  3. 将路径部分的数组减少到最后一个。
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.