Javascript 用Lodash替换或附加到字符串

Javascript 用Lodash替换或附加到字符串,javascript,string,lodash,Javascript,String,Lodash,我有一个包含SQL语句的数组: var sql=[ "select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL ", "select mes,sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL GROUP BY mes" ]; 我需要在每条语句上加一个where子句。 问题是当我有其他子句而不是WHERE子句时,我需要将WHERE子句放在所有其他子句之前。我试着这样做,

我有一个包含SQL语句的数组:

    var sql=[ "select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL ",
              "select mes,sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL GROUP BY mes"
   ];
我需要在每条语句上加一个where子句。 问题是当我有其他子句而不是WHERE子句时,我需要将WHERE子句放在所有其他子句之前。我试着这样做,但运气不好

var clauses=['GROUP','HAVING'];
    _.forEach(sql, function (sq, key) {
        clauses.map(function (clause) {
            if (sq.indexOf(clause) !== -1) {
                debugger;
                sql[key]=[sq.slice(0, sq.indexOf(clause)), ' where '+obj.where_str+' ', sq.slice(sq.indexOf(clause))].join('');

                return false;
            }else{
                debugger;
                sql[key]=sq+" where " + obj.where_str;
                return false;
            }
        });
    });

我建议您使用RegExp来解决您的问题

使用以下RegExp,您可以找到Select是否有组或HAVING运算符

var pattern = /(select.*)((?:GROUP|HAVING).*)/i;
然后可以针对阵列测试此模式:

var arr = ['select mes,sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL GROUP BY mes',
    'select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL ',
    'select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL HAVING sadsa'];

arr.forEach(function(select, index){
    var n = pattern.exec(select); // execute the pattern agains the current Select
    if(!n){ // if it not match any GROUP or HAVING,
        arr[index] += arr[index] + ' your_WHERE '; // append your Where at the end
        return;
    } // if match, append yout Where in the middle
    arr[index] = n[1] + ' your_WHERE ' + n[2];
});
结果将是:

0:"select mes,sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL  your_WHERE GROUP BY mes"
1:"select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL "
2:"select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL  your_WHERE HAVING sadsa"

希望有帮助。

这只是我这边的一次尝试。请看一看

下面的代码将在
from..
语句后面添加新的where子句。所以它永远是第一位的

var str=“从PRS\U CUSTOS\U物料分组中选择金额(custo)作为总计…”;
var newStr='where something>12'
var first_part=str.substr(0,str.indexOf('from')+5);
var第二部分tmp=str.substr(str.indexOf('from')+6);
var second_part=second_part_tmp.substr(0,second_part_tmp.indexOf(“”));
var第三部分=第二部分tmp.substr(第二部分tmp.indexOf(“”));
如果(第二部分索引(“”)!=0){
}
日志(第一部分、第二部分、第三部分);

console.log([first\u part,second\u part,newStr,third\u part].join(“”))
谢谢大家,但我简化了事情。 我只是替换
:其中

var sql=[
                    "select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL :where",
                    "select mes,sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL :where GROUP BY mes"
                ];
使用

_.forEach(sql, function (sq, key) {
        sq=sq.replace(":where", ' where '+obj.where_str);
        sql[key]=sq
    });

请对不起作用的内容提供适当的解释,并提供一个包含示例输入的说明。如果在一条语句中同时包含两个子句,则注释将失败,因为您将在其中插入两次