tags:

views:

848

answers:

2

I would like to take a string

var a = "http://example.com/aa/bb/"

and process it into an object such that

a.hostname == "example.com"

and

a.pathname == "/aa/bb"
+7  A: 

js-uri (available on Google Code) takes a string URL and resolves a URI object from it:

var some_uri = new URI("http://www.example.com/foo/bar");

alert(some_uri.authority); // www.example.com
alert(some_uri);           // http://www.example.com/foo/bar

var blah      = new URI("blah");
var blah_full = blah.resolve(some_uri);
alert(blah_full);         // http://www.example.com/foo/blah
Rex M
thanks!!! butI want to uri = new Location("http://example.com/aa/bb")typeof(window.location) == typeof(uri)
ffffff
Since window.location is a string, I don't really see how that would be possible or helpful. Why do the types need to match when you can easily convert from one to the other?
Rex M
https://developer.mozilla.org/en/DOM/window.location is very nice api!! so I hope convert String to window.location object
ffffff
Setting window.location changes the browser so it is not going to happen.
epascarello
Hmm that's right. window.location is not a string, but can be assigned from a string. I'm not sure if that can be mimicked, I've tried assigning the prototype of location to a new uri object but that did not work.
Rex M
Thank you for an opinion. Would you teach the source code that you tried?
ffffff
+6  A: 
var getLocation = function(href) {
    var l = document.createElement("a");
    l.href = href;
    return l
}
var l = getLocation("http://example.com/path");
console.debug(l.hostname)
>> "example.com"
console.debug(l.pathname)
>> "/path"
ffffff
Are you sure this is a cross-browser compatible solution?
roosteronacid
href is a special DOM attribute type with those additional URI-like properties on it. Very interesting!
Rex M
http://www.devguru.com/technologies/javascript/11177.asp has a nice and concise list of all the attributes you can get from a link. The attributes available are: hash, host, hostname, href, pathname, port, protocol, search, target, text
artlung
It should be noted that, while this may help/answer the original poster, this answer will only work for people doing JS work in a browser, since it relies on the DOM to do its work.
Adam Batkin