Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new Location object in javascript

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?

like image 731
Josh Johnson Avatar asked Jul 09 '10 14:07

Josh Johnson


People also ask

What is location object in JavaScript?

The location object contains information about the current URL. The location object is a property of the window object. The location object is accessed with: window.location or just location.

What is location pathname in JavaScript?

pathname. The pathname property of the Location interface is a string containing the path of the URL for the location, which will be the empty string if there is no path.

What's the difference between window location and document location in JavaScript?

The window. location is read/write on all compliant browsers. The document. location is read-only in Internet Explorer but read/write in Firefox, SeaMonkey that are Gecko-based browsers.


1 Answers

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.

like image 132
Christian C. Salvadó Avatar answered Oct 05 '22 13:10

Christian C. Salvadó