Convert URL String into a Javascript Object

0 min read 128 words

Sometimes you find yourself with a String, something like and you want to repeatably access elements of it correctly.

Let’s say that you want to only get the origin of a URL, or maybe the host, or even protocol, how would you do this?

The URL object

Javascript brings you the URL object, which allows you to instantiate it with a string, and optionally a base to work from.

new URL(url, [base])

By using this object, you can achieve all of this very easily.

new URL("/convert-url-string-into-a-javascript-object")

/*
URL {
  hash: ""
  host: "andrewodendaal.com"
  hostname: "andrewodendaal.com"
  href: "/convert-url-string-into-a-javascript-object"
  origin: "https://andrewodendaal.com"
  password: ""
  pathname: "/convert-url-string-into-a-javascript-object"
  port: ""
  protocol: "https:"
  search: ""
  searchParams: URLSearchParams {}
  username: ""
}
*/

Notice all the useful object keys we can now easily refer to,

Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags