显示网址javascript的最后一部分?

时间:2013-08-12 19:13:50

标签: javascript

我需要使用javascript显示网址的最后一部分!

我正在使用此代码,但这会显示整个网址:

<script language="javascript">

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

</script>

如果网址如下所示:

domain.com/something/file

我只需要显示“文件”。

4 个答案:

答案 0 :(得分:6)

document.write(window.location)写位置的原因是因为toString window.location方法,它真正返回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
  5. (还有端口,搜索(?this=that)和哈希(#hash),在这种情况下都是空的)

    所以,我将something/filesplit带到一个数组中,只要它是/,就是["something", "file"]

    之后我pop ping了数组的最后一部分,在本例中为“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,IE除外),您可以使用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,这使得您无需自己解析搜索字符串。

答案 1 :(得分:2)

<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/

答案 2 :(得分:1)

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

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