【问题标题】:How to get the domain name from anchor href attribute?如何从锚点 href 属性中获取域名?
【发布时间】:2012-03-18 07:47:24
【问题描述】:

我有一个网址,例如:

http://www.intereconomia.com/noticias-gaceta/politica/grinan-los-casos-corrupcion-pueden-influir-20120226

我只想在我的链接文本中:

http://www.intereconomia.com 

但 href 转到:

http://www.intereconomia.com/noticias-gaceta/politica/grinan-los-casos-corrupcion-pueden-influir-20120226

什么正则表达式 jquery 可以做这个功能?

【问题讨论】:

标签: jquery


【解决方案1】:

您可以试试这个干净简单的方法,而不是使用正则表达式。

$('a').each(function(){
    $(this).text(this.protocol + "//" + (this.hostname || this.pathname));
});​

注意:如果您只想为一组锚设置它,则相应地更改选择器,但里面的逻辑保持不变。

工作演示 - http://jsfiddle.net/ShankarSangoli/8G7JM/3/

【讨论】:

  • @hyperrjas - 检查我编辑的答案,现在还添加了protocol 并支持pathname,以防hostname 在某些浏览器中不可用。
【解决方案2】:

听起来您要求一个简单的锚标记(如果您需要一些特定的 jQuery/JavaScript 操作,请详细说明):

<a href="http://www.intereconomia.com/noticias-gaceta/politica/grinan-los-casos-corrupcion-pueden-influir-20120226">
    http://www.intereconomia.com
</a>

【讨论】:

  • 我生成了一个带有 ruby​​ 代码&lt;%= link_to @post.url, @post.url, :target =&gt; "_blank", :class =&gt; "from_url" %&gt;的链接
【解决方案3】:

您可以为链接添加要显示的文本:
&lt;a href="http://www.intereconomia.com/noticias-gaceta/politica/grinan-los-casos-corrupcion-pueden-influir-20120226"&gt;Click Here&lt;/a&gt;

但是,我不建议将文本设置为 http://www.intereconomia.com,因为当用户希望转到 http://www.intereconomia.com 时,链接到内页通常被视为一种不好的做法

改为使用描述性链接来屏蔽网址。

【讨论】:

    【解决方案4】:
    //wait for `document.ready` to fire so the DOM elements are available to modify
    $(function () {
    
        //iterate through all the `<a>` elements in the DOM
        $.each($('a'), function () {
    
            //get the text of the current `<a>` element and then use RegExp to get everything after the `.com/`
            var url   = $(this).text(),
                other = url.replace(/^(http|https):\/\/(.){0,99}(\.com|\.net|\.org)/, '');
    
            //now change the text of this `<a>` element to not display anything after the `.com/`
            $(this).text(url.replace(other, ''));
        });
    });​
    

    ​ 可能有一个更优雅的解决方案,但这应该可以解决问题。

    这是一个演示:http://jsfiddle.net/jasper/DssEs/2/

    【讨论】:

    • 你可以删除结尾的斜线/ http://www.intereconomia.com 没有最后的斜线/。谢谢
    • @hyperrjas 当然,只需要从(.com\/) 中删除\/jsfiddle.net/jasper/DssEs/2
    • 感谢 Jasper,但仅适用于 .com 域。它可能适用于任何域吗?谢谢
    • @hyperrjas 我添加了.net/.org,您可以通过更改这条RegExp来添加更多:(\.com|\.net|\.org),只需添加|\.blah以包含.blah域。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 2015-04-03
    • 2011-08-30
    • 1970-01-01
    • 2016-11-03
    相关资源
    最近更新 更多