View Full Version : Resolved Endless loop

03-27-2012, 02:46 AM
The following bit of javascript grabs a URL, checks whether it contains the string "abcjournals", and if so, replaces any subdomain before the "abcjournals" with "test.abcjournals". e.g. xyz.abcjournals becomes test.abcjournals.

<script type="text/javascript">
var loc = window.location.href;
if (loc.match(/abcjournals/)) {
loc = loc.replace(/[a-z]+\.abcjournals/, "test.abcjournals");

The above code works successfully, except that the page refreshes in an endless loop. If I add a "break;" or "exit;" after the window.location.replace line, there is no endless loop, but the URL string doesn't get replaced as expected.

I've also tried using a "var i = 0;" adding "&& (i===0)" to the IF statement, and incrementing i within the IF statement; but again, the string doesn't get replaced as expected.

Any suggestions much appreciated!

03-27-2012, 03:01 AM
The destination also matches what you are testing against in the if statement.

To fix it you need to change the if condition so that it matches the originating page but not the destination page.

The entire page including the script reloads each time the if statement is satisfied and so there is no value that is retained from one call to the next.

03-27-2012, 03:15 AM
Thanks so much for this! I changed the if line to -

if (loc.match(/[a-z]+\.abcjournals/))

and all works beautifully!