JS - 用查询中的局部变量替换所有字符串

时间:2016-10-19 11:09:54

标签: javascript regex sqlite variables replace

有没有办法用两个同名的变量替换两个@之间的所有字符串?

我从http请求获取'data'对象的所有属性,所以这不是局部变量,所以我不知道两个@之间的值,只知道默认值(filtes,搜索,场)

这就是我得到的:

SELECT名称,年龄,地址,(名称||年龄||地址)AS搜索来自用户WHERE搜索LIKE'%lisboa%'和名称LIKE'%ricardo%'和年龄LIKE'%23%' AND ndos = @ndos @ AND nmdos =' @nmdos @ 'AND 1 = 1;

这就是我需要的:

SELECT名称,年龄,地址,(名称||年龄||地址)AS搜索来自用户WHERE搜索LIKE'%lisboa%'和名称LIKE'%ricardo%'和年龄LIKE'%23%' AND ndos = 615 AND nmdos ='订单'和1 = 1;

这是我的代码:

var ndos = 615,
    nmdos = "Orders";

var data = {
    search:"lisboa",
    fields:{
        name:"ricardo",
        age:23
    },
    filter:"name, age, address",
    query:"SELECT name, age, address @filter@ FROM users WHERE @search@ @fields@ ndos = @ndos@ AND nmdos = '@nmdos@' AND 1 = 1;"
};

var result = data.query;

var fields = "";

for(var i in data.fields) fields += " " + i + " LIKE '%" + data.fields[i] + "%' AND ";

//check if is searchable
var searchable = (result.indexOf('@filter@') !== -1 && result.indexOf('@search@') !== -1) && data.search;

//build search column
result = result.replace(/@filter@/g,searchable ? ", (" + data.filter.replace(/,/g," || ") + ") AS search " : "");

//search value
result = result.replace(/@search@/g,searchable ? " search LIKE '%" + data.search + "%' AND " : "");

//app filters values
result = result.replace(/@fields@/g,fields);

//build search column
console.log(result);

1 个答案:

答案 0 :(得分:1)

最初的想法是这样的。



var myMap = { 'ndos': '615', 'nmdos': 'Orders' };
var keys = [];
var str = "SELECT name, age, address , (name || age || address) AS search FROM users WHERE search LIKE '%lisboa%' AND name LIKE '%ricardo%' AND age LIKE '%23%' AND ndos = @ndos@ AND nmdos = '@nmdos@' AND 1 = 1";
for (var key in myMap) {
  if (myMap.hasOwnProperty(key)) {
   str = str.replace('@' +key + '@', myMap[key])
  }
}
 document.writeln(str);




将这些变量存储在关联数组中,然后使用它替换字符串。