This content originally appeared on Go Make Things and was authored by Go Make Things
This week, we’ll be looking at how to work with URLs and URL query string parameters with vanilla JS. We’re kicking things off today with a look at how to create, parse, and modify URL strings.
Let’s dig in!
Quick aside: today’s article is an excerpt from my new Vanilla JS Short on the URL
and URLSearchParams
APIs.
The new URL() constructor
You can use the new URL()
constructor to create a new URL
object. Pass in an absolute URL string as an argument, or relative URL string and base URL string.
The returned URL
object provides a handful of properties you can use to get, set, and modify aspects of the URL string.
// An absolute URL string
let resources = new URL('https://gomakethings.com/resources');
// A relative URL string and base URL string
let articles = new URL('/articles', 'https://gomakethings.com');
One you have a URL
object, you can use a handful of properties to get details about the URL and manipulate them.
URL Object Properties
The URL
object has a handful of instance properties that can be used to both get and set aspects of a URL string.
Some of the most useful ones include the hostname
, pathname
, hash
, and href
.
// A new URL object
let url = new URL('https://gomakethings.com/checkout#cart?product_id=12374&quantity=42');
// The hostname without a port
// returns "gomakethings.com"
let hostname = url.hostname;
// The URL path
// returns "/checkout"
let path = url.pathname;
// The URL hash
// returns "#cart"
let hash = url.hash;
// The full URL string
// returns "https://LordAwesomesauce:NotVerySecure@gomakethings.com:8000/checkout?product_id=12374&quantity=42#cart"
let href = url.href;
Since these properties are read and write, you can use them modify portions of a URL string.
For example, we can remove the pathname
, update the hash
, and then use the href
property to get an updated URL string.
// Remove the pathname
url.pathname = '';
// Update the hash
url.hash = '#credit-cart';
// Get the updated URL string
let modified = url.href;
Working with query strings
Tomorrow, we’ll take a look at a complement to the URL
object: the URLSearchParams
object.
It can be used to get, set, modify, and delete query string parameter values.
Liked this? Get 15 FREE self-paced JavaScript projects. Each one includes a few short lessons and a template to get you started. Click here to get started.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2023-05-22T14:30:00+00:00) Working with URLs with vanilla JavaScript. Retrieved from https://www.scien.cx/2023/05/22/working-with-urls-with-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.