Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách trích xuất hostname từ URL trong JavaScript

Sử dụng URL API (Hiện đại, khuyên dùng)

var url = new URL("https://example.com/path/page?query=1#hash");
console.log(url.hostname); // "example.com"
console.log(url.host);     // "example.com" (bao gồm port nếu có: "example.com:8080")
console.log(url.origin);   // "https://example.com"
console.log(url.pathname); // "/path/page"

Ví dụ đầy đủ

<!DOCTYPE html>
<html>
<body>
  <script>
    var url = new URL("https://example.com/asdf/asdf/sadf.aspx?blah");
    document.write("Hostname: " + url.hostname);
  </script>
</body>
</html>

Cách cũ (legacy) – tránh dùng

var a = document.createElement('a');
a.href = "https://example.com/path";
console.log(a.hostname); // "example.com"

Cách này hack DOM, không cần thiết khi đã có URL constructor.

Lưu ý

  • new URL() ném lỗi nếu URL không hợp lệ – bọc try/catch.
  • Relative URL cần base: new URL("/path", "https://base.com").
  • Hỗ trợ tốt mọi trình duyệt hiện đại (IE không hỗ trợ – cần polyfill).