我有这个:
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'];
关于javascript - 通过第三个实例拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951220/