2

I've come up with a regex to match terms that contain a certain phrase, which can include letters or numbers, and excludes a dash. For instance, test-123, test123 and test will all be matched by ^[test0-9._-]+$/gi.

However, in MongoDB, I'm not too sure how to dynamically search for it. I've tried,

      const { search } = req.query;

      const regex = new RegExp(`/^[${search}0-9._-]+$/`, "ig");

      const results = await Test.find({ name: { $regex: regex } })

I've also tried

 await Test.find({ name: { $regex: ".*[" + search + "0-9._-]+$.*", $options: "i" } })

As well as just,

      const regex = new RegExp(`/^[${search}0-9._-]+$/`, "ig");

      await Test.find({ name: regex });

Not sure how to get this working, what am I doing wrong?

2 Answers 2

4

Printing new RegExp(/^[${search}0-9._-]+$/, "ig") returns following pattern /\/^[test0-9._-]+$\//gi which is probably not what you're trying to achieve (additional slashes).

You can try this way (tested in Mongo Shell):

let search = "test";
let regex = new RegExp(`^[${search}0-9._-]+$`, "ig");
db.test.find({ name: { $regex: regex } });
Sign up to request clarification or add additional context in comments.

Comments

0

NOTE:

You do not need to wrap the expression in "/" when using "new RegExp." Also, with expressions such as "\b" or anything with a backward slash, you may need to escape it with an extra "\"

For example:
const search = "string"
const regex = new RegExp(\\b${search}\\b, "i");

Prints out: /\bstring\b/i

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.