是否显示URL javascript的最后一部分?
我需要使用javascript显示URL的最后一部分 我正在使用此代码,但这将显示整个URL:是否显示URL javascript的最后一部分?,javascript,Javascript,我需要使用javascript显示URL的最后一部分 我正在使用此代码,但这将显示整个URL: <script language="javascript"> document.writeln(document.location); var url = $(this).attr("href"); var part = url.substring(url.lastIndexOf('/') + 1); </script> document.writeln(documen
<script language="javascript">
document.writeln(document.location);
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
</script>
document.writeln(document.location);
var url=$(this.attr(“href”);
var part=url.substring(url.lastIndexOf('/')+1);
如果URL如下所示:
domain.com/something/file
我只需要显示“文件”。
var segment_str=window.location.pathname;//返回段1/段2/段3/段4
变量段数组=段字符串拆分('/');
var last_segment=segment_array.pop();
文件。写入(最后一段);//警报段4
jsiddle:原因
document.write(window.location)
写入位置是因为window.location
的toString方法,它真正返回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
href:http://example.com/something/file
(还有端口、搜索(?this=that
)和散列(#hash
),在这种情况下都是空的)
因此,我将某物/文件
放入一个数组中,无论这是/
,它将是[“某物”,“文件”]
在此之后,我将ping掉数组的最后一部分,在本例中为“file”
无论是window.location
还是任何),您都可以使用而不是,这样您就不必自己解析搜索字符串。replace(/-/g,“”)和split(.html”)将从url中删除“连字符”和“.html”,从而只保留路径名
var pathname = window.location.pathname,
part = pathname.substr(pathname.lastIndexOf('/') + 1);
var parts=window.location.pathname.split("/");
var query=parts[parts.length-1].split(".html");
query[0]=query[0].replace(/-/g," ");
document.write(query[0])
你可能在做正确的事情;但我认为它只是在第一行写“document.location”。请在末尾尝试document.writeln(part)。用JSFiddle检查我的答案:)使用attr('href')
意味着(假设您知道自己在做什么),您可能试图从元素的href
获取URL,而不是从页面位置获取URL。但我不完全确定你想做什么。“你能再解释一下你的意图吗?”大卫托马斯,不,如果我诚实的话,我真的不知道我在做什么。我已经解释了完全相同的事情,我正试图做的,没有一个答案帮助我到目前为止@DavidThomas,是的,我正在尝试从页面位置获取URL。这不应该是this.location.pathname
?或者window.location.pathname
以获得更多的保证?如果它是锚定标记,则不会,这是我根据问题的上下文假设的。否则,是的:)任何解释都很好。更新了解释这应该是什么?查看JSFIDLE。它可以满足您的需要。:)我确实查过了。它打开一个警报,上面写着“安全”!什么是安全的?!Safe是我在JavaScript中编码的示例URL中的最后一个URI段。代码基本上满足了您的需求。它允许您按照此处的问题要求“显示URL的最后一部分”。我希望我能被选为我努力的最佳解决方案:)而且,我不希望它出现在警报窗口中。我需要它像我自己的例子一样显示在页面上。
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')
var pathname = window.location.pathname,
part = pathname.substr(pathname.lastIndexOf('/') + 1);
var parts=window.location.pathname.split("/");
var query=parts[parts.length-1].split(".html");
query[0]=query[0].replace(/-/g," ");
document.write(query[0])