Problem and Solution
I recently had to write a dynamic router in React. A given URL had to be checked against an API to see if it had any content to display. To do this, I had to verify the pathname coming back from the resource ultimately matched the pathname in the location bar. Having a consistent way to parse URLs was necessary.
I learned that the HTMLAnchorElements actually have a lot of the same properties as the global
location and can be used to parse different URL strings to determine the pathname.
Therefore, to parse my URL strings, I just create a HTMLAnchorElement, assign it an href, and then look at the pathname property.
let a = document.createElement('a'); a.href = "/hello"; console.log(a.pathname); // === '/hello' a.href = "https://dev.to/hello"; console.log(a.pathname); // === '/hello'
Want to mention some things to note before you try this in your application.
First, it fails, for obvious reasons, when there is no scheme on the URL.
let a = document.createElement('a'); a.href = "dev.to/hello"; console.log(a.pathname); // === '/dev.to/hello'
Second, IE11 is not going to add the preceding slash, which can cause inconsistencies.
let a = document.createElement('a'); a.href = "https://dev.to/hello"; console.log(a.pathname); // === 'hello' (IE11) // === '/hello' (Chrome)
What I did to clean this up is just check to see if the first character is a slash and if not just prepend it.
let pathname = a.pathname; if (pathname.substr(0, 1) !== '/') pathname = '/' + pathname;
Hope you found this useful!
Oldest comments (3)
Today you can probably use the URL API developer.mozilla.org/en-US/docs/W...
Good to know! Wish it had IE11 support, but I guess I could use a polyfill.