Midhunsai Midhunsai - 1 year ago 72
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);

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 Source

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


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


es5 code converted online

"use strict";

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download