Skip to content

Convert URL String into a Javascript Object

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])
Code language: JavaScript (javascript)

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

new URL("") /* URL { hash: "" host: "" hostname: "" href: "" origin: "" password: "" pathname: "/convert-url-string-into-a-javascript-object" port: "" protocol: "https:" search: "" searchParams: URLSearchParams {} username: "" } */
Code language: JavaScript (javascript)

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

See also  Square Every Digit in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x