DEV Community

Daniel Wolf
Daniel Wolf

Posted on

6 2

Easy URL Parsing using the DOM

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'

Gotchas

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!

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (3)

Collapse
 
denisinvader profile image
Mikhail Panichev

classic

Collapse
 
ajnasz profile image
Lajos Koszti

Today you can probably use the URL API developer.mozilla.org/en-US/docs/W...

Collapse
 
danwolfdev profile image
Daniel Wolf

Good to know! Wish it had IE11 support, but I guess I could use a polyfill.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay