views:

359

answers:

4

If my javascript ajaxes away to my server and returns an ID of 49 in the plain text format of [49] is there a way in which i an do something like this... (i have tested and doesnt work)

switch(data)
{
    case '[*]':
        (..etc.)
    break;
}

Where the wildcard is the * and i want to make sure it is enclosed within two square parenthesis?

Because i need to check that there wasnt another word returned like error and i am reserving the default for unexpected errors, any ideas? :) Thanks!

A: 

You could try to use if else and regex for matching wildcard patterns.

Assuming data = "[49]"; or any digits inside brackets.

if(/\[\d+\]/.test(data)){
    //do something
}else{
    //default
}
S.Mark
i just saved the data to a var and then set the data to something else if it was correct ;) cheers
tarnfeld
A: 

Short answer: No, switch/case can't handle wildcard.

You should probably do some preprocessing/sanity checking before entering the switch, or simply discard it completely since it's more appropriate for specific case scenarios rather than processing streamlined data. Regexp will serve you better here.

kb
Yes, it can, see my prior post... actually it can handle true for the switch, then evaluate each case. it doesn't have to be fixed values like case statements in other languages.
Tracker1
woot! nice one, didn't know about that.
kb
+2  A: 
Tracker1
A: 

You could create a list of patterns and associated callbacks and do a simple loop and check for matches. For example:

    var patterns = [];

    function myCallback(){ document.write('myCallback!'); }
    function myOtherCallback(){ document.write('myOtherCallback!'); }
    function myLastCallback(){ document.write('You will never see me!'); }

    patterns.push({'pattern':new RegExp(/\[.+\]/),'callback': myCallback});
    patterns.push({'pattern':new RegExp(/.+/),'callback':myOtherCallback});
    patterns.push({'pattern':new RegExp(/A-Z{3}/),'callback':myLastCallback});

    var f = "[49]";
    for(var i=0;i<patterns.length;i++){
        if(patterns[i].pattern.test(f)){
            patterns[i].callback();
        }
    }

Which outputs the following:

myCallback!myOtherCallback!
inkedmn