2012-02-28 49 views
1

我有一个像如网址:如何从锚href属性获取域名?

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可以做到这一点功能?

+0

可能的重复?看到这个问题。 http://stackoverflow.com/questions/1420881/javascript-jquery-method-to-find-base-url-from-a-string – 2012-02-28 19:54:12

回答

6

而不是使用正则表达式,你可以试试这个是干净和简单。

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

注意:如果你想将其设置为仅一套锚,然后相应地改变选择,但内在逻辑是一样的。

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

+0

工作正常:D。谢谢! – hyperrjas 2012-02-28 20:12:31

+0

@hyperrjas - 检查我编辑的答案,现在添加了'protocol'并支持'pathname'以防'hostname'在某些浏览器中不可用。 – ShankarSangoli 2012-02-28 20:38:29

+1

谢谢你现在工作正常:D – hyperrjas 2012-02-28 20:58:46

2

这听起来像你问一个简单的定位代码(如果你需要一些特定的jQuery/JavaScript操作,请详细说明):

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

是这是我的问题:D – hyperrjas 2012-02-28 19:54:42

+0

我生成一个链接与红宝石代码'<% = link_to @ post.url,@ post.url,:target =>“_blank”,::class =>“from_url”%> – hyperrjas 2012-02-28 19:58:42

0

您可以添加文本,以显示该链接:
<a href="http://www.intereconomia.com/noticias-gaceta/politica/grinan-los-casos-corrupcion-pueden-influir-20120226">Click Here</a>

不过,我不会建议作出http://www.intereconomia.com作为通常被认为是一种不好的做法文本当用户希望去http://www.intereconomia.com

链接到内页

请使用描述性链接来掩盖网址。

1
//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/

+0

您可以删除结尾斜杠**/**'http://www.intereconomia .com'没有最后的斜线/。谢谢 – hyperrjas 2012-02-28 20:00:49

+0

@hyperrjas当然,只需从'(.com \ /)'中删除'\ /':http://jsfiddle.net/jasper/DssEs/2/ – Jasper 2012-02-28 20:02:57

+0

谢谢Jasper,但只适用于.com域。它可能适用于任何域?谢谢 – hyperrjas 2012-02-28 20:11:27