Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a wildcard in switch statement

I have data returned from an ajax call: INSERT_OK_something.

I would like to use a switch statement with a wildcard like INSERT_OK_* and pass "something" like a id variable to my url.

switch (data) {
case "ERROR":
        $("#alert").dialog( "open" ).html( "Error" );
        return false;

case "INSERT_OK_*":
    var url = "index.php?op=ok&id=" + something;
    window.location = url ;
    return false; 
}

How would I do this?

like image 564
Paolo Rossi Avatar asked Nov 23 '25 11:11

Paolo Rossi


1 Answers

This little trick will do (see jsFiddle):

var data = "INSERT_OK_BLABLA";

switch (data) {
case "INSERT_OK_" + data.slice("INSERT_OK_".length): // emulate INSERT_OK_*
    var url = "index.php?op=ok&id=" + data.slice("INSERT_OK_".length);
    alert(url);
    break;
default:
    alert("default");
    break;
}

or using startsWith (see jsFiddle):

switch (true) {
case data.startsWith("INSERT_OK_"):
    var url = "index.php?op=ok&id=" + data.slice("INSERT_OK_".length);
    alert(url);
    break;
default:
    alert("default");
    break;
}
like image 190
huysentruitw Avatar answered Nov 24 '25 23:11

huysentruitw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!