0

Here I have handleFilterType function which returns a string dynamically and puts return value into filtered_value variable.

Now I need to pass this filtered_value variable to my match function. So is there any way to pass variable to match function. I tried most but I could not found the solution.

const filtered_value = this.handleFilterType();  // function return string and set into filter_value variable

const getFilterDefaultValues={({ types }) => {
            const match = types.find(type => type.name.match(/filtered_value/i)); //need to pass filtered_value variable into match function
            return match;
      }}
Tech Sourav
  • 124
  • 1
  • 7
  • 1
    Don't use `match`, use `includes` or `indexOf`? – Bergi Jan 02 '20 at 12:08
  • 1
    Does this answer your question? https://stackoverflow.com/questions/4029109/javascript-regex-how-to-put-a-variable-inside-a-regular-expression – V.Volkov Jan 02 '20 at 12:09
  • `/filtered_value/i` is a regex which matches `"filtered_value"`, it does not refer to the variable `filtered_value` in any way. You could create a regex from a string instead by calling the `RegExp` constructor on `filtered_value` instead. – Ivan Jan 02 '20 at 12:11

2 Answers2

1

You can just pass a RegExp object:

type.name.match(new RegExp(filtered_value, 'i'));
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
0

You can do it like below.

const regex = 'hello';
const test = new RegExp(regex);

"hello".match(test);

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

laktherock
  • 427
  • 4
  • 19