Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string by third instance?

Tags:

javascript

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.

like image 225
Borja Avatar asked Dec 18 '22 20:12

Borja


1 Answers

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'];
like image 100
adeneo Avatar answered Dec 21 '22 09:12

adeneo