使用JavaScript或jQuery解析URL

6

假设我有一个URL:

example.com/hello/world/20111020(带或不带尾随斜杠)。 我想做的是从URL中剥离出域名 example.com ,然后将 hello world 20111020 分解成数组。但我的另一个问题是,有时 URL 没有 /hello/world/20111020 或只有 /hello/,所以我需要先确定 example.com 后面是否有任何内容,如果没有,则不做任何操作,因为显然没有可用的内容。然而,如果每个 / 后面都有一些内容,我需要将它们添加到此数组中,并按顺序进行。这样我就可以使用数组 [0] 并知道它是 hello。

我几天前尝试过一些东西,但是在处理尾随斜杠时遇到了问题,它不断破坏脚本,我不幸地放弃了那个想法。今天,我正在寻找新思路。

5个回答

18
这应该有效。
var url = 'example.com/hello/world/20111020/';
//get rid of the trailing / before doing a simple split on /
var url_parts = url.replace(/\/\s*$/,'').split('/'); 
//since we do not need example.com
url_parts.shift(); 

现在url_parts将指向数组["hello", "world", "20111020"]


2
var url = window.location.href; 用于解析当前网址 :) - jave.web
@johnny 你应该获取 url_parts 数组的内容,而不是使用 url_parts.shift() 命令的输出。 - Narendra Yadala

3
您可以使用 jQuery-URL-Parser 插件:
var file = $.url.attr("file"); 

在您的情况下,您可能希望使用segment()函数:
var segments = $.url('http://allmarkedup.com/folder/dir/example/index.html').segment(); 

// segments = ['folder','dir','example','index.html']

2
   <script type="text/javascript">
    function splitThePath(incomingUrl){
     var url = document.createElement("a");
     url.href = incomingUrl;
    //url.hash  Returns the anchor portion of a URL
    //url.host  Returns the hostname and port of a URL
    //url.hostname  Returns the hostname of a URL
    //url.href  Returns the entire URL
    //url.pathname  Returns the path name of a URL
    //url.port  Returns the port number the server uses for a URL
    //url.protocol  Returns the protocol of a URL
    //url.search    Returns the query portion of a URL
    if(url.pathname && url.pathname != ""){
   var pathnameArray = url.pathname.split("/");
 }else{

}


}
</script>

当您首次设置url.href时,客户端浏览器会填充其余的值。 - DefyGravity

0
我已经为URL创建了以下正则表达式。
^https?://(((0|([1-9][0-9]{0,1}))(\.(0|([1-9][0-9]{0,1}))){3})|([a-zA-Z]([a-zA-Z0-9$\-_@\.&+!*"\'\(\),]|(%[0-9a-fA-F][0-9a-fA-F]))*(\.([a-zA-Z]([a-zA-Z0-9$\-_@\.&+!*"\'\(\),]|(%[0-9a-fA-F][0-9a-fA-F]))*))*))(/|((/([a-zA-Z]([a-zA-Z0-9$\-_@\.&+!*"\'\(\),]|(%[0-9a-fA-F][0-9a-fA-F]))*))*))$

这是针对MySql编写的 - 我相信稍微调整一下,你就可以让它满足你的需求。

顺便说一句 - 这个想法是我从一个RFC中得到的,具体编号我现在想不起来了。


0

对于解析URL,一个不同的方法可以是使用锚点DOM对象。

var a = document.createElement("A");
a.href = 'http://example.com:8080/path/to/resources?param1=val1&params2=val2#named-anchor';

a.protocol; // http:
a.host; // example.com:8080
a.hostname; //example.com
a.port; // 8080 (in case of port 80 empty string returns)
a.pathname; // /path/to/resources
a.hash; // #named-anchor
a.search // ?param1=val1&params2=val2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接