2

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
2
  • What is the type of possible example strings? Is it an array? Commented Dec 11, 2019 at 13:39
  • Better suited for codegolf.stackexchange.com Commented Dec 11, 2019 at 13:55

6 Answers 6

3

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");
}

Sign up to request clarification or add additional context in comments.

Comments

2

you could use string.match method

    let str = "log";

    var re = "^(log|del|c|cd)$";
    var found = str.match(re);

    if (found) ....

Comments

2

You could use the includes method on an array...

let str = "log";
let arr = ["log","del","c","ce"];
console.log(arr.includes(str));
// Or as a single statement...
console.log(["log","del","c","ce"].includes(str));

Comments

2

Alternatively you can use indexOf.

let stringToMatch = "log";

let matches = ["ce", "c", "del", "log"];

console.log(matches.indexOf(stringToMatch) !== -1);

Comments

2

You can use an array and its includes() function call:

let str = "log";
let criteria = ["log", "del", "c", "ce"];
console.log(criteria.includes(str));

Comments

0

You could have matching factory and then use it in any place where you need to do multiple matches.

const matchingFactory = (string) => new Proxy({}, {
  get(obj, key, receiver) {
     return (() => !!string.match(new RegExp(key, 'i')))()
  }

})

And then use it in any module or place in your code in the following way:

const _ = matchingFactory('log');

Then you could shorten your example to

console.log(_.log || _.del || _.c || _.ce); //Return if str has a match

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.