Redirecting the browser if a value is found in an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wangers16
    New Member
    • Jul 2007
    • 57

    Redirecting the browser if a value is found in an array

    Hi,

    I have created a validation file in js that will direct users to another page if the link they clicked on is stored on the file however I need the if function contained in the file to work with arrays or a list of some sort

    thnx in advance here is the code I have been working with

    [CODE=javascript]<!--
    function validate(url){
    outlink = url
    str0 = 'page1.htm'
    str1 = 'page2.htm'
    str2 = ''
    if ( outlink == str0 || outlink == str1 || outlink == str2 ){
    outlink = 'error.htm'
    }
    else{
    outlink = outlink
    }
    window.location .href=(outlink)
    }
    // -->[/CODE]
    Last edited by gits; Aug 30 '07, 06:37 PM. Reason: added code tags
  • phvfl
    Recognized Expert New Member
    • Aug 2007
    • 173

    #2
    Hi Wangers,

    The way I would personally do this would be to extend the Array js object through use of the prototype object and add a contains method which returns true if the array contains the string passed in:
    [CODE=javascript]

    Array.prototype .contains=funct ion($str){
    //declare a boolean set to false
    var $blFound = new Boolean();

    //loop through all items in the array
    for (var i = 0;i<this.length ;i++){
    //check if the string for comparisonis in the item in the array.
    if($str==this[i]){
    //if it is change the boolean to true.
    $blFound=true;
    }
    }
    //return the value of the boolean.
    return $blFound;
    }

    [/CODE]

    If this is in your code then all Array objects would have a method called contains which would take a string argument and return true if it matches. Your code could then be rewritten as:
    [CODE=javascript]
    function validate(url){
    outlink = url
    //declare array, declare explicit size if desired.
    var pages = new Array()

    //populate from somewhere...

    //check array and if it contains outlink change the value of outlink.
    if (pages.contains (outlink)){
    outlink = 'error.htm'
    }
    window.location .href=(outlink)
    }
    [/CODE]

    I have removed the else statement as this does not add functionality as it just assigns the value of outlink to itself. The contains is case sensitive as it stands, if you was to add a flag for case insensitivity then this could be done. Let me know if this is the case and you struggle to do this.

    Comment

    • phvfl
      Recognized Expert New Member
      • Aug 2007
      • 173

      #3
      Originally posted by wangers16
      I want case insensitivity
      Quote from PM

      Case insensitivity can be obtained by using a regular expression (regexp) with a i (case insensitive) flag. The other flags available on regexp is g (global) which matches all instances of a string and m which causes multiline to be used.

      Anyway, to put case insensitivity in this case change the contains function to:

      [CODE=javascript]
      Array.prototype .contains=funct ion($str){
      var $blFound = new Boolean();
      var $reg = new RegExp("^" + $str + "$", "i")
      for (var i = 0;i<this.length ;i++){
      if(this[i].match($reg)){
      $blFound=true;
      }
      }
      return $blFound;
      }
      [/CODE]

      The new line creates a regular expression to test against using the match function in the if loop. The "^" forces the expression to match with the start of a line, the "$" forces the expression to march the end of the line (this forces an exact match) I hope this explains:

      Pattern
      Uses "est" "tes" "test"

      None true true true
      ^ false true true
      $ true false true
      ^ and $ false false true

      Let me know if you want more info on this.

      BTW this is a basic use for regexp as it can be used for much more such as testing is a string is a valid email pattern or postcode.

      Comment

      • wangers16
        New Member
        • Jul 2007
        • 57

        #4
        thank you for all of your help the script works great

        Comment

        • pbmods
          Recognized Expert Expert
          • Apr 2007
          • 5821

          #5
          Changed thread title to better describe the problem.

          Comment

          • phvfl
            Recognized Expert New Member
            • Aug 2007
            • 173

            #6
            Originally posted by wangers16
            displays the error page no matter what values I enter into the array even if I put no value at all in there

            please assist

            I put this into the populate area earlier and I was wondering whether or not I was right in doing so
            Code:
                  pages = new Array('page1.htm');
                  pages = new Array('page2.htm');
            You are declaring an new array on each line at the moment. To add multiple pages to the use:
            [CODE=javascript]
            var pages = new Array();
            pages[0]="page1.htm"
            pages[1]="page2.htm"
            pages[2]="page3.htm"
            [/CODE]

            Just increment the index each time. The compare function code will need to be on each page that uses it, and will return true if a match is made.

            If you continue to have problems please post the javascript that you are using so that I can check through it.

            Comment

            • gits
              Recognized Expert Moderator Expert
              • May 2007
              • 5388

              #7
              yep ...

              that's right ... but to mention: a more elegant and performant way to declare and init an array is the following way - i comment the code ... read it carefully :)

              [CODE=javascript]
              /**
              * declaring and initializing arrays
              */

              // declaring the standard way out of every book :)
              var list = new Array();

              // put elements in it
              list[0] = 'val0';
              list[1] = 'val1';

              // put it together in one step
              var list = new Array('val0', 'val1');

              // since we sometimes want to have an empty list (array)
              // we simply declare one ... but! we dont need to use the
              // brackets because js don't need to eval them when we
              // don't put params in ... slightly better version is now:
              var list = new Array;

              // it is better to use literals ... only 2 chars and js don't need
              // to interpret 2 keywords ;) so: best is to use literals when having
              // them
              var list = [];

              // to init values you may use the literals too
              var list = ['val0', 'val1'];
              [/CODE]
              kind regards

              ps: the same goes for objects :)

              Comment

              • phvfl
                Recognized Expert New Member
                • Aug 2007
                • 173

                #8
                Originally posted by gits
                yep ...

                that's right ... but to mention: a more elegant and performant way to declare and init an array is the following way - i comment the code ... read it carefully :)

                [CODE=javascript]
                /**
                * declaring and initializing arrays
                */

                // declaring the standard way out of every book :)
                var list = new Array();

                // put elements in it
                list[0] = 'val0';
                list[1] = 'val1';

                // put it together in one step
                var list = new Array('val0', 'val1');

                // since we sometimes want to have an empty list (array)
                // we simply declare one ... but! we dont need to use the
                // brackets because js don't need to eval them when we
                // don't put params in ... slightly better version is now:
                var list = new Array;

                // it is better to use literals ... only 2 chars and js don't need
                // to interpret 2 keywords ;) so: best is to use literals when having
                // them
                var list = [];

                // to init values you may use the literals too
                var list = ['val0', 'val1'];
                [/CODE]
                kind regards

                ps: the same goes for objects :)
                You live and learn, cheers

                Comment

                • gits
                  Recognized Expert Moderator Expert
                  • May 2007
                  • 5388

                  #9
                  Originally posted by phvfl
                  You live and learn, cheers
                  ;) yep ...all the time

                  but the things i mentioned are things that you encounter when making heavy use of javascript, due to building ajax-applications. sometimes you have huge amounts of data to process ... and than you search for optimizations on everything ;) ... when using js only the way most users do ... there is no explicit need to do or even to know such things ... but in case you DO know and use it that way you may ready for takeoff with more complex things ...

                  kind regards

                  Comment

                  • wangers16
                    New Member
                    • Jul 2007
                    • 57

                    #10
                    Originally posted by phvfl
                    You are declaring an new array on each line at the moment. To add multiple pages to the use:
                    [CODE=javascript]
                    var pages = new Array();
                    pages[0]="page1.htm"
                    pages[1]="page2.htm"
                    pages[2]="page3.htm"
                    [/CODE]

                    Just increment the index each time. The compare function code will need to be on each page that uses it, and will return true if a match is made.

                    If you continue to have problems please post the javascript that you are using so that I can check through it.
                    I have tried both your way and the way that gits mentioned however it still won't work

                    here is a copy of the code at it's current stage:
                    [CODE=javascript]<!--
                    Array.prototype .contains=funct ion($str){
                    var $blFound = new Boolean();
                    var $reg = new RegExp("^" + $str + "$", "i")
                    for (var i = 0;i<this.length ;i++){
                    if(this[i].match($reg)){
                    $blFound=true;
                    }
                    }
                    return $blFound;
                    }
                    function validate(url){
                    outlink = url
                    var pages = new Array;
                    var pages = ['page1.htm', 'page2.htm'];
                    if (pages.contains (outlink)){
                    outlink = 'error.htm'
                    }
                    window.location .href=(outlink)
                    }
                    // -->[/CODE]

                    P.S. is this code server-side?

                    Comment

                    • phvfl
                      Recognized Expert New Member
                      • Aug 2007
                      • 173

                      #11
                      The code is javascript, so it is client side.

                      What is the value that is being passed in for the url variable? If there is trailing information before the filename e.g. url=location/page1.htm then it would not currently match. If this is the case then remove the "^" from the $reg declaration.

                      I have just been playing about with calling this. Even when the return from the contains function is false the code in the if loop was being executed. Change the if loop statement to:
                      [CODE=javascript]
                      if (pages.contains (outlink)==true ){
                      outlink = 'error.htm'
                      }
                      [/CODE]

                      Taking into account what Gits posted the code can be made more efficient by using it as such.
                      [CODE=javascript]
                      Array.prototype .contains=funct ion($str){
                      //removed keywords for new boolean and set it to false directly.
                      var $blFound = false;
                      var $reg = new RegExp("^" + $str + "$", "i")
                      for (var i = 0;i<this.length ;i++){
                      if(this[i].match($reg)){
                      $blFound=true;
                      }
                      }
                      return $blFound;
                      }

                      function validate(url){
                      outlink = url

                      //removed duplicate declaration of variable
                      var pages = ['page1.htm', 'page2.htm'];
                      alert(pages.con tains(outlink)) ;
                      if (pages.contains (outlink)==true ){
                      outlink = 'error.htm'
                      }
                      window.location .href=(outlink)
                      }
                      [/CODE]

                      The comments can be removed and have been included to show the changes.

                      Comment

                      • wangers16
                        New Member
                        • Jul 2007
                        • 57

                        #12
                        Originally posted by phvfl
                        The code is javascript, so it is client side.

                        What is the value that is being passed in for the url variable? If there is trailing information before the filename e.g. url=location/page1.htm then it would not currently match. If this is the case then remove the "^" from the $reg declaration.

                        I have just been playing about with calling this. Even when the return from the contains function is false the code in the if loop was being executed. Change the if loop statement to:
                        [CODE=javascript]
                        if (pages.contains (outlink)==true ){
                        outlink = 'error.htm'
                        }
                        [/CODE]

                        Taking into account what Gits posted the code can be made more efficient by using it as such.
                        [CODE=javascript]
                        Array.prototype .contains=funct ion($str){
                        //removed keywords for new boolean and set it to false directly.
                        var $blFound = false;
                        var $reg = new RegExp("^" + $str + "$", "i")
                        for (var i = 0;i<this.length ;i++){
                        if(this[i].match($reg)){
                        $blFound=true;
                        }
                        }
                        return $blFound;
                        }

                        function validate(url){
                        outlink = url

                        //removed duplicate declaration of variable
                        var pages = ['page1.htm', 'page2.htm'];
                        alert(pages.con tains(outlink)) ;
                        if (pages.contains (outlink)==true ){
                        outlink = 'error.htm'
                        }
                        window.location .href=(outlink)
                        }
                        [/CODE]

                        The comments can be removed and have been included to show the changes.
                        Thanks guys for all of your help it does work correctly now on all parts of my site

                        Comment

                        • gits
                          Recognized Expert Moderator Expert
                          • May 2007
                          • 5388

                          #13
                          hi ...

                          glad to hear you got it to work :) ... post back to the forum anytime you have more questions ...

                          kind regards

                          Comment

                          Working...