Javascript:遍历每一行并删除直到特定字符

时间:2017-07-12 05:14:04

标签: javascript

这是我要处理的日志:

2017-07-03  15:10:40.945    Host -> LOG| Here comes the text I need
2017-07-03  15:10:40.946    Host -> LOG| Here comes the text I need2
2017-07-03  15:10:40.947    Host -> LOG| Here comes the text I need3

目前它仅适用于第一行:

var myText = '...'
var preProcessed = myText.substring(myText.indexOf("|") - 3);

结果(仅适用于第一行):

LOG| Here comes the text I need 
2017-07-03  15:10:40.946    Host -> LOG| Here comes the text I need2 
2017-07-03  15:10:40.947    Host -> LOG| Here comes the text I need3

如何逐行循环以使文本没有日期和时间?

2 个答案:

答案 0 :(得分:0)

您可以按新行拆分,删​​除您不想要的文字,然后将其加入。就像这样。



var log = `2017-07-03  15:10:40.945    Host -> LOG| Here comes the text I need
2017-07-03  15:10:40.946    Host -> LOG| Here comes the text I need2
2017-07-03  15:10:40.947    Host -> LOG| Here comes the text I need3`

var preProcessed = log.split("\n").map(function (l) {
   return l.substring(l.indexOf("|") - 3);
}).join("\n");

console.log(preProcessed);

// you can also use regex like this
var preProcessedUsingRegex = log.replace(/.*->\s/g, '');
console.log(preProcessedUsingRegex);




答案 1 :(得分:0)

你应该首先获得你的数组,然后做你想要的。 像这样:

var lines = text.split('\n');
lines.forEach((line) => {
  console.log(line.substring(line.indexOf("|") - 3))
})