22 August 2024

To parse a URL in JavaScript, you can use the built-in URL object. This provides an easy way to extract and manipulate different parts of a URL.

Source code viewer
  1. const url = new URL('https://example.com:8080/pathname/?search=test#hash');
  2.  
  3. // Accessing various parts of the URL
  4. console.log(url.protocol); // "https:"
  5. console.log(url.hostname); // "example.com"
  6. console.log(url.port); // "8080"
  7. console.log(url.pathname); // "/pathname/"
  8. console.log(url.search); // "?search=test"
  9. console.log(url.hash); // "#hash"
  10. console.log(url.origin); // "https://example.com:8080"
  11. console.log(url.href); // "https://example.com:8080/pathname/?search=test#hash"
Programming Language: Javascript