Euph
Euph

Reputation: 95

Javascript Check if part of string is contained in enum values

I have an enum

 enum YourEnum {
   enum1 = 'Sunday',
   enum2 = 'Monday',
   enum3 = 'Tuesday',
}

and I want to check if some part of word are included in. If for example user tips "mon", i'm expecting that it matches with Monday.

I have two problems: I need to convert values of enum in lowercase, and I need that part of word match.

I tried to do that:

var value = "mon";
if (Object.values(YourEnum).toString().toLowerCase().includes((value))) {
    console.log("some values match")
}

or

const list=Object.values(YourEnum).toString().toLowerCase();
for (let i = 0; i < list.length; i++){
    if (list[i].indexOf("mon") >= 0){
        console.log("some values match", list[i]);
     }
}

But I don't get the results I'm expecting.

Any ideas ?

Upvotes: 0

Views: 2851

Answers (3)

Randy Casburn
Randy Casburn

Reputation: 14165

This code will find the search by filtering the enum for lowercase versions of the enum. Note that StackSnippets doesn't like enum keyword due to babel, so had to include link to TS Playground snippet.

Object.values returns an array that you can use filter on to filter out everything that does not contain the test.

const test: string = 'mon';

enum YourEnum {
   enum1 = 'Sunday',
   enum2 = 'Monday',
   enum3 = 'Tuesday',
}

const out = Object.values(YourEnum).filter(value=>value.toLowerCase().includes(test));
console.log(out);

TS Playground

Upvotes: 0

Paul Braganza
Paul Braganza

Reputation: 151

const list=Object.values(YourEnum).toString().toLowerCase();

When you use above line of code its converting the list to a string

"sunday,monday,tuesday"

You can use the below script to get expected results

const list=Object.values(YourEnum);

for (let i = 0; i < list.length; i++){
    if (list[i].toString().toLowerCase().indexOf("mon")>=0){
        console.log("some values match", list[i]);
     }
}

Upvotes: 1

CRice
CRice

Reputation: 32146

Are you trying to find which item of the enum your search string is matching against? In that case try using the array .find method to check each enum member for a match, returning the first that does:

/*
enum YourEnum {
   enum1 = 'Sunday',
   enum2 = 'Monday',
   enum3 = 'Tuesday',
}
*/

// This is how a typescript enum is transpiled, it is equivalent to the typescript code above.
var YourEnum;
(function(YourEnum) {
  YourEnum["enum1"] = "Sunday";
  YourEnum["enum2"] = "Monday";
  YourEnum["enum3"] = "Tuesday";
})(YourEnum || (YourEnum = {}));

// Here is an example of how it might be done.
const findMatchingDay = search_str =>
  Object.values(YourEnum).find(day => day.toLowerCase().includes(search_str));

console.log(findMatchingDay("mon"));
console.log(findMatchingDay("not_a_day"));

Upvotes: 2

Related Questions