按第三个实例拆分字符串

Splitting string by third instance?

本文关键字:三个 实例 拆分 字符串      更新时间:2023-09-26

>我有这个:

var url = "http://www.example.com/level1/level2"

我想按字符/将 URL 分为 3 个级别。我试过了:

var array = url.split('/');

但输出是这样的:

['http:','','www.example.com','level1','level2']

我想要这个:

['http://www.example.com','level1','level2']

我试过url.split('/')[2]但这不起作用。

为什么不正确解析它

var url = "http://www.example.com/level1/level2"
var a = document.createElement('a');
a.href = url;
a.protocol; // http:
a.host;     // www.example.com
a.pathname; // /level1/level2
var parts = a.pathname.split('/').filter(Boolean);
parts.unshift(a.protocol + '//' + a.host); // ['http://www.example.com','level1','level2'];

@adeneo非常感谢!你的答案真的很简单干净(我不知道解析URL的方法),但是你的答案有一个小错误......(真的很小:))

您的输出是这样的:

['http://www.example.com','','level1','level2']

所以要有我的输出(3 个级别):

var url = "http://www.example.com/level1/level2"
var a = document.createElement('a');
a.href = url;
a.protocol; // http:
a.host;     // www.example.com
a.pathname; // /level1/level2
var parts = a.pathname.split('/');
parts.shift();  // added this line ------------------
parts.unshift(a.protocol + '//' + a.host); 
document.write(parts);

在方法unshift()之前添加parts.shift();,这样输出为真:

['http://www.example.com','level1','level2']

如果我被允许纠正你,请原谅我:)

如果我错了,请告诉我:)再次感谢!