JavaScript 分割 URL 时无法获取片段
我的 JS 经验有限,我需要分割一个看起来像这样的字符串:
进入 http://example.com/ 和 !/about
我不能不幸的是,如果使用 PHP,则无法解析 URL。正确的??
这就是我现在所拥有的:
<script type="text/JavaScript">
var newUrl = window.location.pathname;
var hash=newUrl.split('#');
var f=hash[1];
</script>
我可以对第三行执行此操作:
var hash=newUrl.split('com');
然后计算哈希值,但问题是如果有人访问
example.com/index.php/#!/about
所以我' d 然后必须在这一点之后将我的代码加倍。
有什么想法如何将 URL 分成以哈希为中心的两部分,而不必使用我刚才提到的内容吗?
I have limited JS experience, and I need to split a string that would look something like:
Into http://example.com/ and !/about
I can't unfortuently use PHP and parsing the URL won't work. Right??
This is what I have at the moment:
<script type="text/JavaScript">
var newUrl = window.location.pathname;
var hash=newUrl.split('#');
var f=hash[1];
</script>
I could do this for the 3rd line:
var hash=newUrl.split('com');
And then account for the hash, but the problem with that is if someone goes to
example.com/index.php/#!/about
So I'd then have to double my code after this point.
Any ideas how to split the URL into two parts centring around the hash without having to use what I just mentioned??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
.pathname
不包含哈希值。请改用.hash
属性。使用substring
去除前面的#
字符。The
.pathname
doesn't include the hash. Use the.hash
property instead. Usesubstring
to strip the#
character from the front.如果这不是您的
window.location
,您可以使用/([^:]+://[^/]+)[^#]+#(.*)/ - 您将在第一个和第二个捕获组中获得所需的部分。
If it's not your
window.location
, you can use/([^:]+://[^/]+)[^#]+#(.*)/
- you will get the required parts in the first and second capturing groups.