SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    Confirmed Halfwit
    Join Date
    Oct 1999
    Location
    Vancouver, BC, Canada
    Posts
    983
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to test if string is in an array list?

    I am trying to check and see if a certain file extension is in a list of allowable file extensions. I have the file extension in a string variable, and the list of allowed extensions in an array.

    Code:
    var extension = "txt";
    
    var list = new Array();
    list["1"] = "gif";
    list["2"] = "jpg";
    list["3"] = "png";
    Can anyone show me how to test if "extension" is in the list of allowed extensions? The list of extensions is an unknown number of extensions. (There could be fifty elements in the array..)

    Thanks!
    - A simple online WYSIWYG editor for HTML code snippets.
    - Managed Web Hosting - $3.95/month (resellers welcome)
    - Why pay more? $8.95 domains & $9.95 SSL certificates!

  2. #2
    Perl/Mason Guru Flawless_koder's Avatar
    Join Date
    Feb 2002
    Location
    Gatwick, UK
    Posts
    1,206
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Unfortunately:
    I believe the best way of doing this is to loop through the existing elements and test against them.

    Code:
    for (i=0;i<br.length;i++){
         match=i if (br[i] == nbr);
         }
    You can then refer to your match easily by number. Otherwise you could assign br[i] to match, if you wanted to know the extension name, but this is unlikely since you have nbr (my variable for the extension to test against).

    The only way i can think of doing this faster would be using it the other way round. if you used the extension as the "key" of the array then you could do an "if (exists browsers[key])" Though i'm not entirely certain of this, it's a perl ability that i'm assuming is also possible in JS.
    If you think you'll be doing a lot of testing then it might be worth you creating variables to test against.
    This is wasteful of namespaces - but if you are going to do a lot of testing for extensions then it might save you time.

    Code:
    for (i=0;i<br.length;i++){
         eval('var '+br[i]+' = "'+br_types[i]+'";');
         }
    You can now test simply for "if (eval(br))" since evaluating the extension name would return a variable.

    Hope this helps, and i hope you understand.
    if you don't - don't be afraid to ask for more information - I'll be happy to help in any way that i can.

    Flawless
    ---=| If you're going to buy a pet - get a Shetland Giraffe |=---


Bookmarks

Posting Permissions

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