好吧,假设我有一个网址
example.com/hello/world/20111020(带或不带尾部斜杠)。 我想要做的是从 url 中删除域名 example.com。然后将 hello world 20111020 分解成一个数组。但我的另一个问题是。有时,URL 没有 /hello/world/20111020 或只有 /hello/,所以我需要首先确定 example.com 之后是否有任何内容,如果没有,则不执行任何操作,因为显然没有任何内容可处理。但是,如果每个 / 都有一些东西,我需要将其按顺序添加到该数组中。所以我可以使用 array[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']
<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 创建了以下正则表达式
^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¶ms2=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¶ms2=val2
您可以利用 JS 的 URL 构造函数,并通过将 URL 的
pathnames
值拆分为 pathname
来检索
/
数组
const urlParts = (url) => {
if (!/^https?:\/\//.test(url)) url = `https://${url}`;
const data = new URL(url);
data.pathnames = data.pathname.split("/").filter(Boolean);
return data;
};
console.log(urlParts("example.com/hello/world/20111020").pathnames);
console.log(urlParts("example.com/hello/world/20111020/").pathnames);
console.log(urlParts("example.com/hello/world/20111020?xyz=123").pathnames);
console.log(urlParts("example.com/hello/").pathnames);
console.log(urlParts("example.com").pathnames);