开发者

JavaScript url parsing

I have a url like http开发者_Go百科://mywebsite.com/folder1/folder2/index

How do I parse this above url and get all the values separately? I want the output to be like:

http, mywebsite.com, folder1, folder2, index 


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


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

Then you can use the following attributes:

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

Reference: https://gist.github.com/jlong/2428561


Code

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

var list = s.split("/")

console.log(list);

Output

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜