Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: Endless loop

  1. #1
    New Coder
    Join Date
    Apr 2009
    Posts
    34
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Endless loop

    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.

    Code:
    <script type="text/javascript">
    var loc = window.location.href;
       if (loc.match(/abcjournals/)) {
           loc = loc.replace(/[a-z]+\.abcjournals/, "test.abcjournals");
           window.location.replace(loc);
       }
    /script>
    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!
    Last edited by blinks; 03-27-2012 at 03:48 AM. Reason: resolved

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    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.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    blinks (03-27-2012)

  • #3
    New Coder
    Join Date
    Apr 2009
    Posts
    34
    Thanks
    11
    Thanked 0 Times in 0 Posts
    Thanks so much for this! I changed the if line to -
    Code:
    if (loc.match(/[a-z]+\.abcjournals/))
    and all works beautifully!


  •  

    LinkBacks (?)


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •