I'm about to start a series on URLs and their roles in development. π This is the first part of the series. π Read the full blog, and feel free to comment if you have any quiz. I won't ask for likes; it's up to you. π If I've made any mistakes, please give me feedback. π
URL hu π€, URLs are an essential part of web development. Before diving into URL generation, let's talk about the different components of the URL.
- Protocol/Schema - HTTP, HTTPs, WS
-
Host - www.example.com
- Subdomain - www
- Domain - example
- TLD (Top Level Domain) - .com, .in, .co
-
Path - /forum/questions
- actual path from where you are requesting
-
Query String - /?tag=netwrok&order=newest
- Parameter - {"key": "value"}
- Fragment - #about
Okay, we have seen the different components of the URL. Now, let's talk about how to manage or generate URLs efficiently in JavaScript.
Have a look to the following code
new URL("https://www.example.com/fourm/questions/?tag=network&order=newest")
I created a new instance of the URL class. If you paste this into the browser, you will get an output like this:
If you never used this you might be surprised π€¨. We have a lot in URL. Here I am going to unlock π the power of this URL class.
Add Search Params/Query Params
const myAPI = new URL("https://www.example.com/fourm/questions/?tag=network&order=newest");
myAPI.searchParams.append("limit", 10);
console.log(myAPI.toString())
// https://www.example.com/fourm/questions/?tag=network&order=newest&***limit=10***
Delete Query Params
const myAPI = new URL("https://www.example.com/fourm/questions/?tag=network&order=newest&limit=10");
// before - https://www.example.com/fourm/questions/?tag=network&order=newest&limit=10
******
myAPI.searchParams.delete("order")
// after - https://www.example.com/fourm/questions/?tag=network&limit=10
Update Query Params
const myAPI = new URL("https://www.example.com/fourm/questions/?tag=network&limit=10");
// before - https://www.example.com/fourm/questions/?tag=network&limit=***10***
myAPI.searchParams.set("limit", 20)
// after - https://www.example.com/fourm/questions/?tag=network&limit=***20***
Reading Query Params
const myAPI = new URL("https://www.example.com/fourm/questions/?tag=network&limit=20");
// https://www.example.com/fourm/questions/?tag=network&limit=20
console.log(myAPI.searchParams.get("limit"))
// output - 20
// get all search params
const myAPI = new URL("https://www.example.com/fourm/questions/?tag=network&limit=20");
console.log(myAPI.searchParams.getAll("tag"))
// output - ["network"]
Loop over search params
const myAPI = new URL("https://www.example.com/fourm/questions/?tag=network&limit=20");
myAPI.searchParams.forEach((e, key, parent) => {
console.log(e, key, parent)
// ***value, key, parent***
})
// tag network tag=network&limit=20
// limit 20 tag=network&limit=20
Thanks β₯ for reading π so far, I will be back π in next chapter
Top comments (0)