按第三个实例拆分字符串?

时间:2016-01-22 16:17:42

标签: javascript

我有这个:

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

我想将字符/分成3个级别的网址。我试过了:

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

但输出是这样的:

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

我想这样:

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

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

2 个答案:

答案 0 :(得分:11)

为什么不正确解析

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'];

答案 1 :(得分:0)

@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);

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

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

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

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

相关问题