How to get the domain name from anchor href attribute?

后端 未结 4 1922
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 00:56

I have a url like e.g.:

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

I want on

相关标签:
4条回答
  • 2020-12-22 01:36
    //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/

    0 讨论(0)
  • 2020-12-22 01:39

    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/

    0 讨论(0)
  • 2020-12-22 01:39

    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>
    
    0 讨论(0)
  • 2020-12-22 02:00

    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.

    0 讨论(0)
提交回复
热议问题