New url javascript
Here are some examples of how to use JavaScript to manipulate URLs:
1. Get the current URL:
const url = new URL(window.location.href);
console.log(url.href); // Output: the current URL
2. Get the URL parameters:
const urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.get('param1')); // Output: the value of the 'param1' parameter
3. Set a new URL:
const newUrl = new URL('https://example.com/new-page');
window.location.href = newUrl.href;
4. Add a parameter to the URL:
const url = new URL(window.location.href);
url.searchParams.append('param1', 'value1');
window.location.href = url.href;
5. Remove a parameter from the URL:
const url = new URL(window.location.href);
url.searchParams.delete('param1');
window.location.href = url.href;
6. Update the URL fragment (anchor):
const url = new URL(window.location.href);
url.hash = '#new-anchor';
window.location.href = url.href;
7. Get the URL hostname:
const url = new URL(window.location.href);
console.log(url.hostname); // Output: the hostname of the URL
8. Get the URL path:
const url = new URL(window.location.href);
console.log(url.pathname); // Output: the path of the URL
9. Get the URL protocol:
const url = new URL(window.location.href);
console.log(url.protocol); // Output: the protocol of the URL (e.g. 'https:')
10. Check if the URL is absolute or relative:
const url = new URL('relative-url');
console.log(url.href.includes('://')); // Output: false (relative URL)
const absoluteUrl = new URL('https://example.com/absolute-url');
console.log(absoluteUrl.href.includes('://')); // Output: true (absolute URL)
These are just a few examples of what you can do with JavaScript and URLs.