JavaScript 字符串连接替换第一个字符

JavaScript String concat replaces first character

任务

从日志文件中提取 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>

系统

问题

为什么 ; 没有附加而是替换第一个字符?

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

将提取脚本扩展到 trim 最后一个字符(如果有的话)。

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 有更漂亮的解决方案。