显示URL的最后一部分 javascript?

7
我需要使用Javascript显示URL的最后一部分!
我正在使用这段代码,但是它将显示整个URL:
<script language="javascript">

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

</script>

如果 URL 看起来像这样:domain.com/something/file,我只需要显示 "file"。

2
你可能正在做正确的事情;但我认为只写“document.location”在第一行。试着在结尾处使用document.writeln(part)。 - Katana314
请检查我的答案,使用 JSFiddle :) - Ali Gajani
使用attr('href')意味着(假设您知道自己在做什么),您可能正在尝试从a元素的href中获取URL,而不是页面位置。但我不完全确定您想要做什么。您能更好地解释一下您的意图吗? - David Thomas
@DavidThomas,说实话,我真的不知道自己在做什么。我已经解释了我想要做的事情,但是到目前为止没有任何答案能够帮助我! - Simon Presto
@DavidThomas,是的,我正在尝试从页面位置获取URL。 - Simon Presto
4个回答

14
< p > document.write(window.location) 之所以会输出URL地址,是因为 window.locationtoString方法实际上返回的是 window.location.href

// This will fallback to the location.pathname if this
// is not the location already or not an anchor.
var path = this.pathname || window.location.pathname;
var part = path.split('/').pop();

路径名是域名后面的所有内容。因此,http://example.com/something/file 可以分解为以下几部分:
  1. 协议: http:
  2. 主机名:example.com
  3. 路径名:something/file
  4. href:http://example.com/something/file
(在这种情况下,端口、搜索(?this=that) 和哈希(#hash)也都为空)
因此,我将会使用split函数将something/file按照斜杠/进行分割,并将其转换为数组,即["something", "file"]
接着,我将使用pop函数弹出数组中的最后一个元素,即在本例中的“file”。
window.location和任何<a>标签都具有这些属性。因此,如果需要解析URL,则可以在JavaScript中执行以下操作:
var anchor = document.createElement('a');
anchor.href = '/about'; // this could be any relative or absolute url

现在,如果需要,anchor 将拥有所有这些属性。不需要使用正则表达式或其他任何东西。


更新

在较新的浏览器中(除非您使用 url-polyfill),您可以使用 URL 替代 <a />,如下所示:

const url = new URL('/about', this.location)
// or if you don't care about the host, you can do the following
// const url = new URL('http://localhost/about')

这个包含所有其他信息,加上url.searchParams,使您不必自己解析搜索字符串。


这不应该是 this.location.pathname 吗?或者为了更保险,使用 window.location.pathname - Hashem Qolami
不过,如果它是一个锚标签,那么就不行了,这也是我根据问题的上下文所假设的。否则,可以的 :) - kalley
如果需要解释,请告知。 - Simon Presto
更新了,附上解释。 - kalley

8
<script type="text/javascript">

var segment_str = window.location.pathname; // return segment1/segment2/segment3/segment4
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment); // alerts segment4

</script>

JsFiddle: http://jsfiddle.net/HNMV3/1/


这是什么意思? - Simon Presto
看看这个 JSFiddle,它可以做你想要的。 :) - Ali Gajani
我已经检查过了。它会弹出一个警告框并显示“安全”!什么是“安全”? - Simon Presto
安全是我在JavaScript中编码的示例URL中的最后一个URI段。该代码基本上实现了您想要的功能。它允许您“显示URL的最后一部分”,就像您在这里提问的那样。我希望我的努力能得到投票并被选为最佳解决方案 :) - Ali Gajani
另外,我不希望它出现在警告窗口中。我需要它像我的示例一样显示在页面上。 - Simon Presto
显示剩余3条评论

1
var pathname = window.location.pathname,
    part = pathname.substr(pathname.lastIndexOf('/') + 1);

0

使用replace(/-/g," ")和split(".html")将从URL中删除"连字符"和".html",因此只保留路径名。

var parts=window.location.pathname.split("/");
var query=parts[parts.length-1].split(".html");
query[0]=query[0].replace(/-/g," ");
document.write(query[0])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接