hyperrjas
hyperrjas

Reputation: 10744

How to get the domain name from anchor href attribute?

I have a url like e.g.:

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

I want only in my link text:

http://www.intereconomia.com 

but the href go to:

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

What regex jquery can do this functionality?

Upvotes: 1

Views: 7466

Answers (4)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Instead of using a regex you can try this which is clean and simple.

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

Note: If you want to set it only for set of anchors, then change the selector accordingly but the logic inside remains the same.

Working demo - http://jsfiddle.net/ShankarSangoli/8G7JM/3/

Upvotes: 6

Jasper
Jasper

Reputation: 76003

//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, ''));
    });
});​

​ There is probably a more elegant solution but this should do the trick.

Here is a demo: http://jsfiddle.net/jasper/DssEs/2/

Upvotes: 1

jzworkman
jzworkman

Reputation: 2703

You can add text to display for the link:
<a href="http://www.intereconomia.com/noticias-gaceta/politica/grinan-los-casos-corrupcion-pueden-influir-20120226">Click Here</a>

However, I would not suggest making the text http://www.intereconomia.com as that is usually seen as a bad practice to link to an inner-page when the user is expecting to go to http://www.intereconomia.com

Instead use a descriptive link to mask the url.

Upvotes: 1

James Hill
James Hill

Reputation: 61812

It sounds like you're asking for a simple anchor tag (if you need some specific jQuery/JavaScript action, please elaborate):

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

Upvotes: 2

Related Questions