使用JavaScript或jQuery解析URL

chr*_*ris 5 javascript url jquery parsing slug

好的,我想说我有一个URL

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

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

Nar*_*ala 16

这应该工作

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(); 
Run Code Online (Sandbox Code Playgroud)

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

  • `var url = window.location.href;` 解析当前 url :) (2认同)