如何从anchor href属性获取域名?

时间:2012-02-28 19:52:08

标签: jquery

我有一个网址,例如:

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

什么是regex jquery可以执行此功能?

4 个答案:

答案 0 :(得分:6)

您可以尝试使用正则表达式,而不是使用正则表达式。

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

注意:如果您只想为锚点设置它,那么相应地更改选择器,但内部逻辑保持不变。

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

您可以添加要显示链接的文字:
    <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

时,通常会将其视为链接到内页的不良做法

而是使用描述性链接来屏蔽网址。

答案 3 :(得分: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/

相关问题