Encoding & Decoding URLs
encodeURI(uri)
→ Encodes a full URI but does not encode :/?#&=
.
decodeURI(encodedUri)
→ Decodes a URI processed by encodeURI()
.
encodeURIComponent(component)
→ Encodes a single URI component (more strict, encodes :/?#&=
).
decodeURIComponent(encodedComponent)
→ Decodes a component processed by encodeURIComponent()
.
console.log(encodeURI("my page.asp")); // "my%20page.asp"
console.log(decodeURI("my%20page.asp")); // "my page.asp"
console.log(encodeURIComponent("my page.asp")); // "my%20page.asp"
console.log(decodeURIComponent("my%20page.asp")); // "my page.asp"
Creating & Parsing URLs
new URL(url)
→ Creates a URL object.
url.hostname
→ Gets the domain name.
url.pathname
→ Gets the path of the URL.
url.searchParams
→ Provides methods to handle query parameters.
const url = new URL("<https://example.com/path?name=John&age=25>");
console.log(url.hostname); // "example.com"
console.log(url.pathname); // "/path"
console.log(url.searchParams.get("name")); // "John"
console.log(url.searchParams.get("age")); // "25"
Resolving & Normalizing URLs
url.href
→ Gets or sets the full URL.
url.origin
→ Gets the origin (protocol + hostname + port
).
url.protocol
→ Gets or sets the protocol (e.g., https:
).
url.toString()
→ Converts the URL object to a string.
const myUrl = new URL("<https://example.com:8080/path>");
console.log(myUrl.href); // "<https://example.com:8080/path>"
console.log(myUrl.origin); // "<https://example.com:8080>"
console.log(myUrl.protocol); // "https:"
console.log(myUrl.toString()); // "<https://example.com:8080/path>"
Manipulating Query Parameters
url.searchParams.get(name)
→ Gets the value of a query parameter.