JavaScript url解析

Ra.*_*Ra. 5 javascript parsing

我有一个像http://mywebsite.com/folder1/folder2/index这样的网址

如何解析上面的url并分别获取所有值?我希望输出如下:

http, mywebsite.com, folder1, folder2, index 
Run Code Online (Sandbox Code Playgroud)

Dan*_*llo 4

如果您的 URL 保存在变量中,您可以使用 split() 方法执行以下操作:

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';
Run Code Online (Sandbox Code Playgroud)

如果你想解析文档的当前 URL,你可以这样做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';
Run Code Online (Sandbox Code Playgroud)