Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change internal links to external in jquery or javascript

Im working on a aplication witch gets its content from a different website. In the obtained content are sometimes internal links. I need to add the http://www.olddomain.com to the href value of those links, to make sure they will still work in my aplication.

The data is in a variable: text

variable text contains:

<p style="text-align: right;">
    Lots of text in here, with all kind of html tags, <br /><br /> 
    when suddenly a link appears:
    <a href="/niceinternalpage.html">Here!</a>
</p>

Output i need:

<p style="text-align: right;">
    Lots of text in here, with all kind of html tags, <br /><br /> 
    when suddenly a link appears:
    <a href="www.olddomain.com/niceinternalpage.html">Here!</a>
</p>

Thanks in advance!

like image 926
Denny Beulen Avatar asked Jan 19 '26 09:01

Denny Beulen


2 Answers

You don't need jQuery to perform this operation in modern browsers, you can make use of document.getElementsByTagName to fetch all the a tags on the page:

// document.getElementsByTagName returns a `NodeList` - it looks like an `Array`
// but lacks all of the methods; so we use `Array.prototype.slice` to turn it
// into a 'real' `Array` so we can filter and loop over it.
aTags = Array.prototype.slice.call(document.getElementsByTagName("a")),
    externalUrl = "http://www.olddomain.com";

// Make use of `filter` to return an Array of all `a` tags whose `href` attribute
// is unqualified (eg: does not start with `http`, again you may wish to make this
// filtering logic more complex).
//
// We then chain a `forEach` call to the result of the `filter` call which prepends
// the `externalUrl` to the `a` tag's `href` attribute.
aTags
    .filter(function (aTag) { 
        return aTag.href.match(/^http/) === null;
    })
    .forEach(function(unqualifiedATag) { 
        var unqualifiedUrl = unqualifiedATag.href;

        // Add a leading forward slash.
        if (unqualifiedUrl.charAt(0) !== "/") {
            unqualifiedUrl = "/" + unqualifiedUrl;
        }

        // Update the aTag's href attribute to fully qualify it.
        unqualifiedATag.href = externalUrl + unqualifiedATag.href;
    }); 
like image 184
JonnyReeves Avatar answered Jan 21 '26 23:01

JonnyReeves


You can use attr() to assign change the value of href

Live Demo

$(variable).find('a').attr('href', function(idx, attrValue){ 
   return 'http://www.olddomain.com' + attrValue;
});
like image 38
Adil Avatar answered Jan 21 '26 21:01

Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!