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
3 Answers
Reset to default 4If 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"]