Paolo Rossi Paolo Rossi - 5 months ago 66
Javascript Question

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?

Answer

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;
}
Comments