JavaScript String concat替换第一个字符

时间:2015-10-22 13:55:17

标签: javascript node.js windows string concatenation

任务

从日志文件中提取SQL语句后,我执行简单的字符串连接以在末尾附加;

var query = line[i] + ";"

问题

它应该是什么样的:insert into [...];

它的外观如下:;nsert into [...]

途径

我尝试了不同的连接机制,发现只有附加的连接失败。

for (i in lines) {
  var txt = lines[i];
  console.log(txt);                 // "insert into"
  console.log(txt.concat(";"));     // ";nsert into"
  console.log(txt + ";");           // ";nsert into"
  console.log(txt+=";");            // ";nsert into"
  console.log(";" + txt);           // ";insert into"
}

提取脚本

var fs = require('fs');
var array = fs.readFileSync('file').toString().split("\n");
var result = [];

var currentRow;
var line;
var value;

// loop through all lines of the file
for(i in array) {
    line = array[i];
    // if there is an insert statement, push it on the array
    if (line.lastIndexOf("insert into", 0) === 0) {
      result.push(line);
    // if there is a binding param, interpolate that into the recent insert statement
    } else if (line.lastIndexOf("binding param", 0) === 0){
      value = line.split(" - ")[1].replace("\n", "").replace("\r", "");
      // hibernate represents null as <null> while oracle needs ""
      if (value === "<null>") {
        value = '""';
      // if there is a string, put "" around
      } else if (isNaN(value)) {
        value = '"' + value + '"';
      }
      currentRow = result[result.length-1];
      // interpolate
      currentRow = currentRow.replace("?", value);
      result[result.length-1] = currentRow;
    }
}

数据偷看

insert into <user>.<table> (<col1>, <col2>, <col3>) values (?, ?, ?)
binding parameter [1] as [<type>] - <value>
binding parameter [2] as [<type>] - <value>
binding parameter [3] as [<type>] - <value>

系统

  • Windows 7
  • Node.js v4.2.1

问题

为什么;没有附加,但会替换第一个字符?

1 个答案:

答案 0 :(得分:1)

Pointy所示,字符串中有一个终止回车字符(ASCII 13十进制)。

扩展提取脚本以修剪最后一个字符(如果有的话)。

if (line.lastIndexOf("insert into", 0) === 0) {
   if (line.charCodeAt(line.length - 1) == 13) {
     line = line.substring(0, line.length - 1);
   }
   result.push(line);
   console.log(line); // "insert into [...];"
}

注意:使用regex提供更漂亮的解决方案。