Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change domain portion of links with javascript or jquery

Sorry for my original question being unclear, hopefully by rewording I can better explain what I want to do.

Because of this I need a way to use JavaScript (or jQuery) to do the following:

  • determine domain of the current page being accessed
  • identify all the links on the page that use the domain www.domain1.com and replace with www.domain2.com

i.e. if the user is accessing www.domain2.com/index then:

<a href="www.domain1.com/contentpages/page.html">Test 1</a>

should be rewritten dynamically on load to

<a href="www.domain2.com/contentpages/page.html">Test 1</a>

Is it even possible to rewrite only a portion of the url in an href tag?

like image 926
mpriney Avatar asked Dec 17 '22 09:12

mpriney


2 Answers

Your code will loop over all links on the page. Here's a version that only iterates over URLS that need to be replaced.

var linkRewriter = function(a, b) {
    $('a[href*="' + a + '"]').each(function() {
        $(this).attr('href', $(this).attr('href').replace(a, b));
    });
};

linkRewriter('originalDomain.com', 'rewrittenDomain.com');
like image 194
rooney Avatar answered Dec 22 '22 00:12

rooney


I figured out how to make this work.

<script type="text/javascript"> 
// link rewriter
$(document).ready (
    function link_rewriter(){ 
        var hostadd = location.host;
        var vendor = '999.99.999.9';
        var localaccess = 'somesite1.';

        if (hostadd == vendor) { 
            $("a").each(function(){
                var o = $(this);
                var href = o.attr('href');
                var newhref;
                newhref = href.replace(/somesite1/i, "999.99.999.99");
                o.attr('href',newhref);
            });
        }
    }
);
</script>
like image 20
mpriney Avatar answered Dec 21 '22 22:12

mpriney