Is JavaScript able to to parse arbitrary URLs the same way the current URL is parsed in windows.location?
-
26-06-2021 - |
Question
I like that the current address is nicely split up into sections in window.location
, but I would like to be able to take an arbitrary URL and split it up following the exact same logic. I don't know how window.location
handles corner cases and rare scenarios, so I would like to avoid doing this manually if possible. Since the browser is already doing this work on the current address I'm hoping it contains a function that can do it to any address.
If there are any nice cross-browser libraries (perhaps jQuery plugins) out there I'd love to hear about them too.
Solution 2
Using the info in Xander's answer I've written a small function that parses an URL and returns an object with the desired information. I thought I'd share it here:
function parse_url(url)
{
var e = document.createElement('a');
e.href = url;
return {
'protocol': e.protocol,
'hostname': e.hostname,
'host': e.host,
'port': e.port,
'pathname': e.pathname,
'search': e.search,
'hash': e.hash
}
}
OTHER TIPS
You could create an a
(HTML Anchor Element) element in JavaScript and specify the href
attribute. Then you'll be able to call the properties associated with an anchor element, hash
, protocol
, host
, port
etc...
https://developer.mozilla.org/en-US/docs/DOM/HTMLAnchorElement