JavaScript URL解析

5
3个回答

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';

如果你想解析当前文档的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';

3
var reader = document.createElement('a');
reader.href = "http://test.example.com:80/pathname/?query=param#hashtag";

然后您可以使用以下属性:

reader.protocol
reader.hostname
reader.port
reader.pathname
reader.search
reader.hash
reader.host;

参考资料:https://gist.github.com/jlong/2428561 这是一个关于IT技术的参考资料。

0

代码

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

var list = s.split("/")

console.log(list);

输出

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接