I have fetched window.location into a variable. Now, I want to remove part of the string from the href within the location object, but still retain the object.
In other words, I want to modify the location object, and still be able to use window.location.protocol and window.location.host, but those functions need to work on the modified object.
For example, something like this where my browser displays "https://my.domain.org/site":
var thisloc = window.location;
Modify the href within that object to "http://my.domain.org/othersite"
//now I want it to fetch "http" instead of "https" based on my modified object
var thisprot = thisloc.protocol;
Will that work? If it does, it would be very nice. Otherwise, I have to parse the URL to get the protocol, host and pathname from a modified href, which would also accomplish the same goal.
Inspired by James Padosley’s post on Parsing URLs with the DOM!, the trick here is to use an anchor element (
<a>) as a URL builder/parser. With any anchor element, if you set itshrefproperty to some URL, it will be parsed by the DOM. Thereafter, you can freely modify the parts of that URL via properties on the anchor element. Query thehrefproperty at any time to see the full URL.Using the example from the question…
At this point the anchor element’s href will now be
http://my.domain.org/othersite, as requested. Here’s a JS Bin demonstrating it in action: http://jsbin.com/omoqen/1/edit.The beauty is that anchor elements have the same URL component properties as the
window.locationobject: