使用JavaScript或jQuery解析URL

好的,我想说我有一个URL

example.com/hello/world/20111020(带或不带斜杠)。 我想做的是从域example.com中删除url。 然后打破你好世界20111020成一个arrays。 但我的另一个问题是。 有时URL没有/ hello / world / 20111020或者只是/ hello /所以我需要先确定example.com之后是否有任何内容,如果没有,那么什么都不做,因为显然没有什么可以使用的。 但是,如果每个/我都需要按顺序将它添加到此数组中。 所以我可以使用数组[0]并知道它是你好的。

几天前我尝试了一些东西,但遇到了拖尾斜线的问题,它一直打破了剧本,我遗憾地放弃了这个想法。 今天我正在寻找新的想法。

这应该工作

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"]

您可以使用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'] 
   

我为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中获取了这个想法 – 此时此数字逃脱了我

对于解析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