且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用jquery ..从URL获取域名?

更新时间:2023-02-23 20:28:34

在浏览器中

您可以使用<a>元素来利用浏览器的URL解析器:

In a browser

You can leverage the browser's URL parser using an <a> element:

var hostname = $('<a>').prop('href', url).prop('hostname');

或没有jQuery:

var a = document.createElement('a');
a.href = url;
var hostname = a.hostname;

(此技巧对于解析相对于当前页面的路径特别有用.)

(This trick is particularly useful for resolving paths relative to the current page.)

使用以下功能:

function get_hostname(url) {
    var m = url.match(/^http:\/\/[^/]+/);
    return m ? m[0] : null;
}

像这样使用它:

get_hostname("http://example.com/path");

这将返回http://example.com/,如示例输出所示.

This will return http://example.com/ as in your example output.

如果仅尝试获取当前页面的主机名,请使用document.location.hostname.

If you are only trying the get the hostname of the current page, use document.location.hostname.