最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript url parsing - Stack Overflow

programmeradmin0浏览0评论

I have a url like

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

http, mywebsite, folder1, folder2, index 

I have a url like http://mywebsite./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., folder1, folder2, index 
Share edited Dec 21, 2012 at 3:21 PhearOfRayne 5,0503 gold badges33 silver badges44 bronze badges asked May 5, 2010 at 5:04 Ra.Ra. 9554 gold badges18 silver badges30 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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

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

// path[0]     === 'http:';
// path[2]     === 'mywebsite.';
// 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.'
// path[1]                   === 'folder1';
// path[2]                   === 'folder2';
// path[3]                   === 'index';
var reader = document.createElement('a');
reader.href = "http://test.example.: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./jlong/2428561

Code

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

var list = s.split("/")

console.log(list);

Output

["http:", "", "mywebsite.", "folder1", "folder2", "index"]
发布评论

评论列表(0)

  1. 暂无评论