I have this:
var url = "http://www.example.com/level1/level2"
I would like to split the URL in 3 levels by the character /
. I tried:
var array = url.split('/');
But the output is this:
['http:','','www.example.com','level1','level2']
I would like this:
['http://www.example.com','level1','level2']
I tried url.split('/')[2]
but that doesn't work.
Why not parse it properly
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'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With