URL API
The URL API provides a standard way to create, parse, and modify URLs. It is much more robust and easier to use than regex-based string manipulation for handling web addresses.
1. Creating a URL Object
You can create a URL object by passing a URL string to the constructor. You can also pass a base URL as a second argument.
// Absolute URL
const myUrl = new URL('https://example.com/path/index.html?id=123#top');
// Relative URL with base
const relativeUrl = new URL('/api/users', 'https://example.com');
console.log(relativeUrl.href); // "https://example.com/api/users"
2. Accessing Components
The URL object breaks down the address into its components.
const url = new URL('https://user:pass@example.com:8080/p/a/t/h?query=string#hash');
console.log(url.protocol); // "https:"
console.log(url.username); // "user"
console.log(url.password); // "pass"
console.log(url.hostname); // "example.com"
console.log(url.port); // "8080"
console.log(url.pathname); // "/p/a/t/h"
console.log(url.search); // "?query=string"
console.log(url.hash); // "#hash"
console.log(url.origin); // "https://example.com:8080"
3. Modifying URLs
You can modify the properties directly, and the href property will update automatically.
const url = new URL('https://example.com');
url.pathname = '/new-path';
url.search = '?q=hello';
console.log(url.href); // "https://example.com/new-path?q=hello"
4. URLSearchParams
The searchParams property returns a URLSearchParams object, which provides methods to work with the query string.
const url = new URL('https://example.com?foo=1&bar=2');
const params = url.searchParams;
// Get values
console.log(params.get('foo')); // "1"
// Check existence
console.log(params.has('bar')); // true
// Add/Set values
params.append('baz', '3');
params.set('foo', '100'); // Overwrites existing 'foo'
// Delete
params.delete('bar');
// Iterate
params.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
// Output:
// foo: 100
// baz: 3
console.log(url.href);
// "https://example.com/?foo=100&baz=3"
5. Static Methods
URL.createObjectURL(blob): Creates a DOMString containing a URL representing the object given in the parameter (File, Blob, or MediaSource).URL.revokeObjectURL(objectURL): Releases an existing object URL which was previously created by callingURL.createObjectURL().
programming/javascript/vanilla/javascript programming/javascript/vanilla/file-api