我想获取 URL 在最后一个 /
之后和查询字符串之前的部分。
到目前为止,我有 URL 的最后一部分,但我无法从 URL 中删除查询字符串。
Javascript:
<script type='text/javascript'>
var url = window.location.href;
var array = url.split('/');
var lastsegment = array[array.length-1];
document.write(lastsegment);
</script>
URL的结构是这样的:
http://www.example.com/search/People?&results=latest
我只需要 People
部分。在上面的 Javascript 中怎么可能呢?
或者有更好的方法吗?
最佳答案
尝试使用 window.location.pathname
而不是 window.location.href
。它仅获取服务器名称和查询字符串(在您的情况下为 "/search/People"
)之间的文本:
var last_part = window.location.pathname.split('/').pop();
您可以阅读有关路径名
的更多信息here .
关于javascript - 拆分 URL 和查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21937345/