使用JavaScript或jQuery解析URL [英] parse URL with JavaScript or jQuery

查看:167
本文介绍了使用JavaScript或jQuery解析URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,假设我有一个网址

Ok lets say I have a URL

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

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.

推荐答案

这应该有效

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 将指向数组 [你好,世界,20111020]

这篇关于使用JavaScript或jQuery解析URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆