tags:

views:

80

answers:

2

Hi,

I have a url like http://mywebsite.com/folder1/folder2/index

how to parse this above url and get all the values separately? I want the output like http, mywebsite.com, folder1, folder2, index

Thanks in adavance

+2  A: 

If your URL is held in a variable, you can use the split() method to do the following:

var url = 'http://mywebsite.com/folder1/folder2/index';
var path = url.split('/');

// path[0]     === 'http:';
// path[2]     === 'mywebsite.com';
// path[3]     === 'folder1';
// path[4]     === 'folder2';
// path[5]     === 'index';

If you want to parse the current URL of the document, you can work on window.location:

var path = window.location.pathname.split('/');

// window.location.protocol  === 'http:'
// window.location.host      === 'mywebsite.com'
// path[1]                   === 'folder1';
// path[2]                   === 'folder2';
// path[3]                   === 'index';
Daniel Vassallo
Thanks .... it works....
Ra
A: 

Code

var s = "http://mywebsite.com/folder1/folder2/index";

var list = s.split("/")

console.log(list);

Output

["http:", "", "mywebsite.com", "folder1", "folder2", "index"]
Peter McGrattan