JavaScript url解析
我有一个像 如何解析上述url并分别获取所有值? 我希望输出如下所示:JavaScript url解析,javascript,parsing,Javascript,Parsing,我有一个像 如何解析上述url并分别获取所有值? 我希望输出如下所示: http, mywebsite.com, folder1, folder2, index 如果URL保存在变量中,则可以使用split()方法执行以下操作: var url = 'http://mywebsite.com/folder1/folder2/index'; var path = url.split('/'); // path[0] === 'http:'; // path[2] === 'm
http, mywebsite.com, folder1, folder2, index
如果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';
如果要分析文档的当前URL,可以使用窗口。位置:
var path = window.location.pathname.split('/');
// window.location.protocol === 'http:'
// window.location.host === 'mywebsite.com'
// path[1] === 'folder1';
// path[2] === 'folder2';
// path[3] === 'index';
代码
var s = "http://mywebsite.com/folder1/folder2/index";
var list = s.split("/")
console.log(list);
输出
["http:", "", "mywebsite.com", "folder1", "folder2", "index"]
然后可以使用以下属性:
reader.protocol
reader.hostname
reader.port
reader.pathname
reader.search
reader.hash
reader.host;
参考:
reader.protocol
reader.hostname
reader.port
reader.pathname
reader.search
reader.hash
reader.host;