Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check multiple strings shorter, JS?

I want to check a string if it matches one or more other strings. In my example i just used 4 possible string values. How can i write this code shorter if i have to check for more values?

//Possible example strings: "ce", "c", "del", "log"
let str = "log"; //My input
console.log(str == "log" || str == "del" || str == "c" || str == "ce"); //Return if str has a match
like image 754
RoyBlunk Avatar asked Mar 19 '26 07:03

RoyBlunk


1 Answers

You could use string test here along with an alternation:

var input = "log";
if (/^(?:log|del|c|ce)$/.test(input)) {
    console.log("MATCH");
}
else {
    console.log("NO MATCH");
}
like image 66
Tim Biegeleisen Avatar answered Mar 21 '26 19:03

Tim Biegeleisen



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!