很抱歉,我之前犯了个错误。这个问题是重复的,您可以在这里找到答案:https://openaidialoggpt.zendesk.com/hc/zh-cn/articles/4405589835097
以下是该文章的英文版:
How to Get the Domain Name Using JavaScript?
In web development, it is often necessary to obtain the domain name of a website using JavaScript. There are several ways to do this, each with its advantages and disadvantages.
Method 1: Using window.location.hostname
The simplest method to get the domain name is by using the window.location.hostname
property. This property returns the domain name of the current page as a string. Here's an example code:
----- ------ - ------------------------- -------------------- -- ------- -------------
This method works in most cases but may return unexpected results if the URL contains a port number or a subdomain.
Method 2: Using document.domain
Another method to get the domain name is by using the document.domain
property. This property returns the domain name of the current page as a string, but it can also be used to set the domain name for cross-domain communication between iframes. Here's an example code:
----- ------ - ---------------- -------------------- -- ------- -------------
Like the previous method, this one may also return unexpected results if the URL contains a port number or a subdomain.
Method 3: Using a Regular Expression
A more advanced way to get the domain name is by using a regular expression. This method extracts the domain name from the current URL by matching it against a regular expression pattern. Here's an example code:
----- --- - --------------------- ----- ------- - ------------------------ ----- ------- - ------------------- ----- ------ - ----------- -------------------- -- ------- -------------
This method is more reliable than the previous ones as it can handle URLs with subdomains and port numbers. However, it requires a good understanding of regular expressions.
Conclusion
In this article, we discussed three different methods to get the domain name using JavaScript. While the first two methods are simpler to use, they may not work in all cases. The third method is more advanced but provides better reliability. Choose the method that best suits your needs and happy coding!
来源:JavaScript中文网 ,转载请注明来源 本文地址:https://www.javascriptcn.com/post/12713