我需要使用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
我只需要显示“文件”。
答案 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
就像这样打破了:
http:
example.com
something/file
http://example.com/something/file
(还有端口,搜索(?this=that
)和哈希(#hash
),在这种情况下都是空的)
所以,我将something/file
和split
带到一个数组中,只要它是/
,就是["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])