我如何得到一个url的最后一段?我有下面的脚本,显示点击锚标记的完整url:

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

如果url为

http://mywebsite/folder/file

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


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

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

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

同时,

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

你也可以使用lastIndexOf()函数来定位URL中/字符最后出现的位置,然后使用substring()函数返回从该位置开始的子字符串:

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

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

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

alert(href.replace(/.*\//, ''));
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));

使用本机pathname属性,因为它是最简单的,并且已经被浏览器解析和解析过了。$(this).attr("href")可以返回类似../..这样就不会得到正确的结果。

如果你需要保留搜索和哈希(例如foo?Bar #baz from http://quux.com/path/to/foo?bar#baz)使用这个:

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

Var部分= 'http://mywebsite/folder/file'.split('/'); var lastSegment = parts.pop() || parts.pop();//处理潜在的尾随斜杠 console.log (lastSegment);

我知道,已经太迟了,但对于其他人来说: 我强烈推荐使用PURL jquery插件。PURL的动机是url也可以用“#”来分割(例如:angular.js links),即url可以看起来像

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

or

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

使用PURL,您可以很容易地决定(segment/fsegment)您想要获得的段。

对于“经典”的最后一部分,你可以这样写:

    var url = $.url('http://test.com/dir/index.html?key=value');
    var lastSegment = url.segment().pop(); // index.html

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

var url = document.URL

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

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

url.split('/').filter(function (s) { return !!s }).pop()
// 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.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
var targetValue = loc.substring(loc.lastIndexOf('/') + 1);

targetValue = 1

如果你的url看起来像:

http://test.com/one/

or

http://test.com/one

or

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

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

现在,因为您需要最后一项,所以运行下一步来加载最初需要的值(targetValue)。

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

// Store original location in loc like: http://test.com/one/ (ending slash) let loc = "http://test.com/one/index.htm"; console.log("starting loc value = " + loc); // If the last char is a slash trim it, otherwise return the original loc loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/')); let targetValue = loc.substring(loc.lastIndexOf('/') + 1); console.log("targetValue = " + targetValue); console.log("loc = " + loc);

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

抄自这个答案

只是正则表达式的另一个解。

var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
window.location.pathname.split("/").pop()

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

window.location.href.substr(window.location.href.lastIndexOf('/') +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

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

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

我使用regex和split:

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

最后它将忽略# ?& /结束url,这种情况经常发生。例子:

https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm

https://cardsrealm.com/profile/cardsRealm / hello ->再turns cardsRealm

https://cardsrealm.com/profile/cardsRealm?hello ->再动画cardsRealm

https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm

你可以先删除末尾的/,然后获取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);

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

最好使用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来说,有一个可用的腻子(如果你在乎的话)。

返回最后一段,不考虑后面的斜杠:

瓦尔瓦尔= http://mywebsite/folder/file//’。分裂(' / ')。布尔(过滤器)pop (); 控制台日志(val);

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

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

最短的方法如何获得URL最后一段与split(), filter()和pop()

函数getLastUrlSegment(url) { 返回新的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这')); console.log(getLastUrlSegment('https://x.com/last带空格的段'));

对我有用。

我知道它是旧的,但如果你想从一个URL得到这个,你可以简单地使用:

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

document.location.pathname从当前URL获取路径名。 获取下面Regex最后一次出现的索引,在我们的例子中是/..点表示任意字符,因此,如果/是URL上的最后一个字符,则不算数。 Substring将截断两个索引之间的字符串。

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

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

最简单的方法是使用location。search

你可以在这里查找更多信息 这里

你可以用简单的路径(w/0)查询字符串等来做到这一点。

虽然可能过于复杂,可能不是高性能的,但我想使用reduce是为了它的乐趣。

  "/foo/bar/"
    .split(path.sep)
    .filter(x => x !== "")
    .reduce((_, part, i, arr) => {
      if (i == arr.length - 1) return part;
    }, "");

在路径分隔符上拆分字符串。 过滤掉空字符串路径部分(这可能发生在路径的末尾斜杠)。 将路径部分数组减少到最后一个。

使用RegEx获取最后一段

str.replace(/.*\/(\w+)\/?$/, '$1');

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

let str =“http://mywebsite/folder/ fill”; 让我们把它放在一起。$ / ' $ '); 游戏机。log (lastSegment);

获取URL最后一段删除(-)和(/)的最佳方法

 jQuery(document).ready(function(){
        var path = window.location.pathname;
        var parts = path.split('/');
        var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash
        lastSegment = lastSegment.replace('-',' ').replace('-',' ');
        jQuery('.archive .filters').before('<div class="product_heading"><h3>Best '+lastSegment+' Deals </h3></div>');
    
    }); 

一种避免查询参数的方法

const urlString = "https://stackoverflow.com/last-segment?param=123" const url =新的url (urlString); url。搜索= "; const lastSegment = url.pathname.split('/').pop(); console.log (lastSegment)

这就是塞巴斯蒂安·巴斯的答案。

如果href是你正在解析的变量,new URL会抛出TypeError,所以为了安全起见,你应该尝试- catch

try{    
    const segments = new URL(href).pathname.split('/');
    const last = segments.pop() || segments.pop(); // Handle potential trailing slash
    console.log(last);
}catch (error){
    //Uups, href wasn't a valid URL (empty string or malformed URL)
    console.log('TypeError ->',error);
}