Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Get Different Part of a URL</title> </head> <body> <script> // Prints complete URL document.write(window.location.href + "<br>"); // Prints protocol like http: or https: document.write(window.location.protocol + "<br>"); // Prints hostname with port like localhost or localhost:3000 document.write(window.location.host + "<br>"); // Prints hostname like localhost or www.example.com document.write(window.location.hostname + "<br>"); // Prints port number like 3000 document.write(window.location.port + "<br>"); // Prints pathname like /products/search.php document.write(window.location.pathname + "<br>"); // Prints query string like ?q=ipad document.write(window.location.search + "<br>"); // Prints fragment identifier like #featured document.write(window.location.hash); </script> <p><strong>Note:</strong> If the URL does not contain a specific component (e.g., port number, and fragment identifier here), it will be set to ''.</p> </body> </html>