Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  29] [ 7]  / answers: 1 / hits: 32475  / 14 Years ago, fri, july 9, 2010, 12:00:00

Is it possible to create a new Location object in javascript? I have a url as a string and I would like to leverage what javascript already provides to gain access to the different parts of it.



Here's an example of what I'm talking about (I know this doesn't work):



var url = new window.location(http://www.example.com/some/path?name=value#anchor);
var protocol = url.protocol;
var hash = url.hash;
// etc etc


Is anything like this possible or would I essentially have to create this object myself?


More From » url-parsing

 Answers
118

Well, you could use an anchor element to extract the url parts, for example:



var url = document.createElement('a');
url.href = http://www.example.com/some/path?name=value#anchor;
var protocol = url.protocol;
var hash = url.hash;

alert('protocol: ' + protocol);
alert('hash: ' + hash);



It works on all modern browsers and even on IE 5.5+.



Check an example here.


[#96291] Tuesday, July 6, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;