使用 JavaScript 或 jQuery 解析 URL
好吧,假设我有一个 URL
example.com/hello/world/20111020 (带或不带尾部斜杠)。 我想要做的是从 url 中删除域名 example.com。然后将 hello world 20111020 分解成一个数组。但我的另一个问题是。有时,URL 没有 /hello/world/20111020 或只有 /hello/,所以我需要首先确定 example.com 之后是否有任何内容,如果没有,则不执行任何操作,因为显然没有任何内容可处理。但是,如果每个 / 都有一些东西,我需要将其按顺序添加到该数组中。所以我可以使用 array[0] 并知道这是你好。
几天前我尝试了一些东西,但遇到了尾随斜杠的问题,它不断破坏脚本,不幸的是我放弃了这个想法。今天我正在寻找新的想法。
Ok lets say I have a URL
example.com/hello/world/20111020 (with or without the trailing slash).
What I would like to do is strip from the url the domain example.com. and then break the hello world 20111020 into an array. But my other problem is. Sometimes the URL has no /hello/world/20111020 or just /hello/ so I need to first determine if there is anything after example.com if there not, then do nothing as obviously there's nothing to work with. However if there is something there for each / I need to add it to this array in order. So I can work with the array[0] and know it was hello.
I tried something a couple days back but was running into issues with trailing slashes it kept breaking the script, I unfortunately abandoned that idea. And today I am looking for fresh ideas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这应该可以工作
现在
url_parts
将指向数组["hello", "world", "20111020"]
。This should work
Now
url_parts
will point to the array["hello", "world", "20111020"]
.您可以使用 jQuery-URL-Parser 插件:
在您的情况下,您可能想要使用
segment()
:You can use the jQuery-URL-Parser plugin:
In your case you'd probably want to use
segment()
:我已经为 URL 创建了以下正则表达式,
它是为 MySql 编写的 - 我相信只要稍微摆弄一下,您就可以让它满足您的需求。
顺便说一句 - 我从 RFC 中得到了这个想法 - 现在我忘记了这个数字
I have created the following regular expression for URLs
It has been written for MySql - I am sure with a bit of fiddling you can get it you work for your needs.
BTW - I took the idea from an RFC - The number escapes me at this moment
对于解析 URL,一种不同的方法是使用锚 DOM 对象。
For parsing URLs, one different approach can be using anchor DOM object.
您可以使用 JS 的 URL 构造函数,并且通过将 URL 的
pathname
值按/
拆分来检索pathnames
数组You could make use of JS's URL constructor, and retrieve the
pathnames
array by splitting the URL'spathname
value by/