Click to See Complete Forum and Search --> : Changing Link URL with JavaScript


jaredwalczak
12-08-2003, 01:43 PM
Hello. I am dynamically generating some pages that have link URLS in the format of "/folder/page.html" (no domain name listed). I want the links to include the proper domain, not MY domain, and was hoping a JavaScript could take care of this "on the fly."

I set up an external .js file with the following code:

--------

for (var i=0; i<document.links.length; i++) {
if (document.links[i].href.indexOf('/') > -1) {
document.links[i].href = "http://www.realdomain.com/"+document.links[i].href+"";
}
}

--------

I thought this would work, but the end result looks like this: http://www.realdomain.com/http://www.mydomain.com/folder/page.html

Can anyone tell me how to change the .js file to get rid of that wrong assumed domain name that is automatically added to the page so that I can link to these pages properly?

Thanks for your time.

Sincerely,
Jared

TheBearMay
12-08-2003, 02:18 PM
Since it's a consistant 11 characters:


var tempStr;
for (var i=0; i<document.links.length; i++) {
if (document.links[i].href.indexOf('/') > -1) {
tempStr=document.links[i].href.substring(11,document.links[i].href.length);
document.links[i].href = "http://www.realdomain.com/"+tempStr+"";
}
}

fredmv
12-08-2003, 02:28 PM
<script type="text/javascript">
//<![CDATA[
onload = function()
{
var a = document.links;
for(var i=0; i<a.length; i++)if(/^http/.test(a[i].href))a[i].href = 'http://www.realdomain.com/'+a[i].href.substring(a[i].href.lastIndexOf('/')+1, a[i].href.length);
}
//]]>
</script><ul>
<li><a href="http://www.mydomain.com/file1.html" onclick="alert(this.href);return false;">http://www.mydomain.com/file1.html</a></li>
<li><a href="http://www.mydomain.com/file2.html" onclick="alert(this.href);return false;">http://www.mydomain.com/file2.html</a></li>
<li><a href="http://www.mydomain.com/file3.html" onclick="alert(this.href);return false;">http://www.mydomain.com/file3.html</a></li>
</ul>