0

in Typescript, I need to expand a variable inside a regular expression to build a filter for a MongoDB query; none of the following solutions seem to be valid; only the variable "code" is expanded, not the "subCode"; suppose we have:

let code = "code1";
let subCode = "CODE2.";
const regexExpression = {code: { $in: [`${code}`, /^`${subCode}`\..*/i] }};

const newRegexExpression = new RegExp(/code: { $in: [`${code}`, /^`${subCode}`\..*/i] }/i
);

Desired result:

{ "code" : { $in : [ "code1", /^"CODE2\.".*/i ] } }
adiga
  • 34,372
  • 9
  • 61
  • 83
user1
  • 556
  • 2
  • 6
  • 22
  • Why do you have
    tags in the code?
    – Simon Lundberg Jan 05 '23 at 10:31
  • Sorry, typo; I have modified the code. – user1 Jan 05 '23 at 10:37
  • I corrected minor flaws in your syntax to better focus the real problem about the impossible expectation. First of all, if you are using a template string literal for your regex pattern, you should use it properly wrapping the whole string with upticks ``RegExp(`code: { $in: [${code}, /^${subCode}\..*] }`, i);``. But anyway are you sure you need such regex? – Diego D Jan 05 '23 at 10:43
  • `new RegExp()` should be used in the place where you have the regex literal now, not on the entire object. So, `{code: { $in: [code, new RegExp(\`^${subCode}\` ) ] }}`. Also, you have to escape the string passed to the RegExp constructor: [Is there a RegExp.escape function in JavaScript?](https://stackoverflow.com/questions/3561493) – adiga Jan 05 '23 at 10:52
  • Tried with const newRegexExpression = new RegExp(`\``{code: { $in: [${code}, /^${subCode}\..*/i] }}`\``,"i"); but now the mondodb nodejs client fails the deleteMany() command: 'MongoServerError: BSON field 'delete.deletes.q' is the wrong type 'regex', expected type 'object' – user1 Jan 05 '23 at 10:59
  • I think I need to express the regular expression as a literal and not with the constructor. – user1 Jan 05 '23 at 11:05

0 Answers0