如何使用jquery ..从URL获取域名? [英] How to get Domain name from URL using jquery..?

查看:69
本文介绍了如何使用jquery ..从URL获取域名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有eq的域名.

1) http://www.abc.com/search 
2) http://go.abc.com/work

我从上述URL仅获得域名

I get only domain name from the above URL

输出类似

1) http://www.abc.com/
2) http://go.abc.com/

我该怎么办?

推荐答案

在浏览器中

您可以使用<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.

这篇关于如何使用jquery ..从URL获取域名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆