如何在查询到mongodb时用数组中的斜杠替换字符串值?

时间:2016-10-14 09:58:22

标签: javascript arrays mongodb

我正在尝试将来自html的数组值存储在服务器端mongodb中。数组以字符串的形式出现,例如[“home”,“sports”],但我需要以斜线数组的形式存储,即[/ home /,/ sports /]。我尝试在javascript中使用替换功能,但我没有这样做。

这是我尝试的代码:在我的服务器端控制器中:

 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"]
              }
            }
          }
        }

1 个答案:

答案 0 :(得分:1)

如果要将String Array转换为RegEx数组,可以使用RegEx constructor和Array map()

ES6:

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

console.log(regexArray);
&#13;
&#13;
&#13;

es5代码converted online

"use strict";

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

console.log(regexArray);