0

I have this search controller and I want to set it up to check every letter in search input but I don't know how to do it with regex.

module.exports.search = (req, res, next) => {
  Character.find({
    $or: [
      { firstName: req.query.search },
      { lastName: req.query.search }
    ]
  })
    .then(characters => {
      res.status(200).send(characters);
    })
    .catch(next);
}

Also, I have tried with

{ firstName: /req.query.search/ }

, but it doesn't work. Any help would be great.

3
  • 1
    See stackoverflow.com/questions/49270331/… and also stackoverflow.com/questions/10728043/… Commented Nov 5, 2019 at 11:51
  • are you getting req.query.search or not ??? Commented Nov 5, 2019 at 11:55
  • @PrakashKarena I am not getting anything when I use regex. req.query.search works perfectly fine without it, but I need to check all letters from the query, not just full string. I hope I explained it well Commented Nov 5, 2019 at 11:57

1 Answer 1

0

I found a solution. I needed to create function to place the whole regex, and then to pass req.query to it inside of controller

module.exports.search = (req, res, next) => {
  if (req.query.search) {
    const regex = new RegExp(escapeRegex(req.query.search), "gi");

    Character.find({
      $or: [{ firstName: regex }, { lastName: regex }]
    })
      .then(characters => {
        res.status(200).send(characters);
      })
      .catch(next);
  }
};

function escapeRegex(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.