Midhunsai Midhunsai - 17 days ago 6
Javascript Question

How to replace the string value with slashes in an array while querying into mongodb?

I am trying to store the array value coming from html in the server side mongodb. the array is coming in the form of strings ie for example ["home","sports"] but i need to store in the form of slash array ie [/home/,/sports/]. i tried with using replace function in javascript but i failed doing that.

Here is my code what I tried: in my server side controller:

var sample = [];
sampleArray = ["home","sports"]; //coming from html search query.

if(sampleArray != 0){
for (var i = 0; i < sampleArray .length; i++) {
var eg3 = sampleArray [i];
console.log('value form an array' + eg3);
sample.push(eg3);

}
var test = sample.replace(/"/g, "/");
}

// querying my DB
mongoQuery = {
ProCat: {
$elemMatch: {
"title": {
$in: test //expected output [/home/,/sports/] but i am getting ["home","sports"]
}
}
}
}

Answer

If you want to convert a String Array to RegEx array, you can use RegEx constructor and Array map().

es6:

const regexArray = ["home","sports"].map(x=>new RegExp(x));

console.log(regexArray);

es5 code converted online

"use strict";

var regexArray = ["home", "sports"].map(function (x) {
  return new RegExp(x);
});

console.log(regexArray);