2

Regex and variables seem to be a current issue here, yet I didn't find an answer to my problem.

It is quite simple, i am using a noSQL database system for javascript called nedb. pretty neat by the way. GitHub link

Here is the part that matters for us :

// Finding all planets whose name contain the substring 'ar' using a regular expression
db.find({ planet: /ar/ }, function (err, docs) {
  // docs contains Mars and Earth
});

as you see, the expression /ar/ means "containing the substring ar", which is classic regex. What I want is replacing ar by a variable (the result of a user search).

Like this : 
var search = ‘ar'; //taken from an HTML form
db.find ({planet : ‘/‘ + search + ‘/‘}, fonction (err,docs) {
}

This unfortunately does not work. Neither does :

  var search = ‘/ar/'; 
    db.find ({planet : search}, fonction (err,docs) {
    }

Do you have any ideas ? Might seem prettu obvious to you, but i am losing my mind on this issue aha ! thank you guys

zoranc
  • 2,410
  • 1
  • 21
  • 34

2 Answers2

2

Use the RegExp constructor :

db.find({ planet: new RegExp(yourString) }, function (err, docs) {

If your string can be anything, you'd better escape it. See this related answer then.

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

You need to use the RegExp constructor, but this alone is not enough (. would be "any character", ? would mean the previous character is optional and / would break your regex, as well as all the other regular regex keywords and characters).

You can avoid this by using a regex escaping function (such aspreg_quote from PHPJS) which will escape them:

db.find({ planet: new RegExp(preg_quote(searchString, '/')) }, function (err, docs) {
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102