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
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
Share
Improve this question
asked Dec 11, 2019 at 13:36
RoyBlunkRoyBlunk
6110 bronze badges
2
- What is the type of possible example strings? Is it an array? – Mayank Patel Commented Dec 11, 2019 at 13:39
- Better suited for codegolf.stackexchange. – nice_dev Commented Dec 11, 2019 at 13:55
6 Answers
Reset to default 3You 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");
}
you could use string.match method
let str = "log";
var re = "^(log|del|c|cd)$";
var found = str.match(re);
if (found) ....
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));
Alternatively you can use indexOf.
let stringToMatch = "log";
let matches = ["ce", "c", "del", "log"];
console.log(matches.indexOf(stringToMatch) !== -1);
You can use an array and its includes() function call:
let str = "log";
let criteria = ["log", "del", "c", "ce"];
console.log(criteria.includes(str));
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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745577372a4634048.html
评论列表(0条)