最后一段网址

时间:2011-01-21 11:11:58

标签: javascript jquery

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

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

如果网址是

http://mywebsite/folder/file

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

28 个答案:

答案 0 :(得分:304)

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

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

这样,您就可以避免创建包含所有网址细分的数组,如split()所做的那样。

答案 1 :(得分:127)

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

console.log(lastSegment);

答案 2 :(得分:51)

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

答案 3 :(得分:25)

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

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

答案 4 :(得分:16)

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

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

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

答案 5 :(得分:9)

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

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

答案 6 :(得分:8)

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

答案 7 :(得分: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

答案 8 :(得分:5)

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

为此,最好使用URL对象,以获得更可靠的解决方案。它是对当前URL的解析解释:

输入class AlarmCreateView(LoginRequiredMixin, CreateView): """ CreateView for User to create the Alarm object """ model = Alarm form_class = SetAlarmForm template_name = 'weather_alarm/set_alarm.html' login_url = "/login/" def form_valid(self, form): self.create_alarm_object(request, form) return super().form_valid(form) def get_success_url(self, **kwargs): return reverse("weather_alarm:active-alarm", kwargs={'pk':self.object.pk}) def create_alarm_object(self, request, form): """ Function to get User's location from IP and create Alarm object """ ... alarm_object = Alarm.objects.create( alarm_id=uuid.uuid4(), user=self.request.user, timezone=user_timezone, city=location.raw['address']['city'], country=location.raw['address']['country'], time=form.cleaned_data['time'].astimezone(pytz.timezone(user_timezone)), temp_conditional=form.cleaned_data['temp_conditional'], surf_conditional=form.cleaned_data['surf_conditional'], temp_max=form.cleaned_data['temp_max'], temp_min=form.cleaned_data['temp_min'], surf_max=form.cleaned_data['surf_max'], surf_min=form.cleaned_data['surf_min'], ) alarm_object.save()

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

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

这适用于所有常见的浏览器。只有我们垂死的IE不支持(并且不会)。对于IE,有polyfills可用(如果您完全care)。

答案 9 :(得分:4)

以Frédéric的答案为基础,仅使用javascript:

var url = document.URL

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

答案 10 :(得分:3)

此外,

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

答案 11 :(得分:3)

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

使用本机pathname属性,因为它最简单,并且已被浏览器解析和解析。 $(this).attr("href")可以返回../..之类的值,这些值无法为您提供正确的结果。

如果您需要保留searchhash(例如来自foo?bar#baz的{​​{1}}),请使用此字段:

http://quux.com/path/to/foo?bar#baz

答案 12 :(得分:3)

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

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

答案 13 :(得分: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);

答案 14 :(得分:2)

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

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

答案 15 :(得分:2)

返回最后一个段,而不管斜杠是什么

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

console.log(val);

答案 16 :(得分:2)

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

this answer

复制

答案 17 :(得分:1)

您可以先删除结尾的/,然后再获取url的最后一部分

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

答案 18 :(得分: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);

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

test.com/path-name = path-name

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

答案 19 :(得分:0)

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

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

答案 20 :(得分: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

答案 21 :(得分:0)

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

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

答案 22 :(得分: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);

为我工作。

答案 23 :(得分:0)

var url = window.location.pathname;
 var urlsplit = url.split("/");
  var result= urlsplit[urlsplit.length-1];
       result will get the Last segment of URL

答案 24 :(得分:0)

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

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

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

答案 25 :(得分:0)

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

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

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

您可以查找更多信息here  和here

答案 26 :(得分: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. 将路径部分的数组减少到最后一个。

答案 27 :(得分:0)

使用 RegEx

获取最后一个细分
str.replace(/.*\/(\w+)\/?$/, '$1');

$ 1表示使用捕获组。在RegEx(\ w +)中使用来创建第一个组,然后将整个字符串替换为捕获组。

let str = 'http://mywebsite/folder/file';
let lastSegment = str.replace(/.*\/(\w+)\/?$/, '$1');
console.log(lastSegment);

相关问题