用lodash替换字符串

时间:2016-09-29 13:37:55

标签: javascript string lodash

我有一个具有多个属性的对象,我想用字符串替换它。

replaceBy:{
          "PRS_JOBS_MAQUINA":"PRS_JOBS_WORKCENTER",
          "CD_MAQ":"CD_WKC",
          "DT_INI_MAQ":"DT_INI_WKC",
          "DT_INI_JM" :"DT_INI_JW"
          }

有没有雄辩的方法用lodash做到这一点? 这是字符串

" 

AND ( CD_JOB, DT_INI_JOB ) IN  (SELECT x.CD_JOB, x.DT_INI_JM FROM PRS_JOBS_MAQUINA x WHERE x.EMPRESA = ':EMPRESA' AND x.CD_MAQ = ':CD_MAQ' AND TO_CHAR(x.DT_INI_MAQ, 'YYYY-MM-DD') = ':DT_INI_MAQ'
AND TO_CHAR(x.DT_INI_JM, 'YYYY-MM-DD') = '1900-01-01'  AND x.DT_FIM IS NULL )

"

3 个答案:

答案 0 :(得分:2)

解决方案:

var yourString = 'your string';
_.forEach(replaceBy, function(value, key) {
    yourString = _.replace(string, key, value);
});

答案 1 :(得分:1)

您可以将replace与包含所有搜索字词的正则表达式一起使用,并使用function replaceByMap(str, replaceBy) { var search = new RegExp(Object.keys(replaceBy).join('|'), 'g'); // creates a regexp of the strings to replace return str.replace(search, function(match) { // iterates the string, and replace the strings found with their replacements from the map return replaceBy[match]; }); } var replaceBy = { "PRS_JOBS_MAQUINA": "PRS_JOBS_WORKCENTER", "CD_MAQ": "CD_WKC", "DT_INI_MAQ": "DT_INI_WKC", "DT_INI_JM": "DT_INI_JW" }; var str = "AND ( CD_JOB, DT_INI_JOB ) IN (SELECT x.CD_JOB, x.DT_INI_JM FROM PRS_JOBS_MAQUINA x WHERE x.EMPRESA = ':EMPRESA' AND x.CD_MAQ = ':CD_MAQ' AND TO_CHAR(x.DT_INI_MAQ, 'YYYY-MM-DD') = ':DT_INI_MAQ' AND TO_CHAR(x.DT_INI_JM, 'YYYY-MM-DD') = '1900-01-01' AND x.DT_FIM IS NULL )"; var result = replaceByMap(str, replaceBy); console.log(result);回调替换它们:

std::vector<Table1> table1Array;
auto ap = wrk.prepared(GetTable1FuncName).exec();
auto aps = wrk.prepared(GetTable2FuncName).exec();
auto pos = aps.begin();
for (auto row = ap.begin(); row != ap.end(); ++row) {
    std::vector<Table2> table2Array;
    while (pos != aps.end()
           && row["table1_id"].as(int()) == pos["table1_id"].as(int())) {
        table2Array.push_back(Table2(pos["first_id"].as(int()), 
                                     pos["second_string"].as(std::string())));
        ++pos;
    }

    Table1 tb1(row["table1_id"].as(int()), row["column2"].as(int()),
               row["column3"].as(int()), row["column4"].as(int()),
               table2Array);

    table1Array.push_back(tb1);
}

答案 2 :(得分:0)

为什么要使用图书馆?

&#13;
&#13;
 var replaceBy={
              "PRS_JOBS_MAQUINA":"PRS_JOBS_WORKCENTER",
              "CD_MAQ":"CD_WKC",
              "DT_INI_MAQ":"DT_INI_WKC",
              "DT_INI_JM" :"DT_INI_JW"
              }, str=  "AND ( CD_JOB, DT_INI_JOB ) IN  (SELECT x.CD_JOB, x.DT_INI_JM FROM PRS_JOBS_MAQUINA x WHERE x.EMPRESA = ':EMPRESA' AND x.CD_MAQ = ':CD_MAQ' AND TO_CHAR(x.DT_INI_MAQ, 'YYYY-MM-DD') = ':DT_INI_MAQ' AND TO_CHAR(x.DT_INI_JM, 'YYYY-MM-DD') = '1900-01-01'  AND x.DT_FIM IS NULL )"

for (var rb in replaceBy) {
  str = str.replace(new RegExp(rb, "g"),replaceBy[rb]);
}
console.log(str)
&#13;
&#13;
&#13;