user10475036
user10475036

Reputation:

Node js string parser

I have an log array.

[ '1539024146 17827 add number 1',
  '1539024146 18826 start calculation',
  '1539024146 18826 end calculation',
  '1539024146 18826 14',
  '1539024146 18826 update number 1 1',
  '1539024146 18826 start calculation',
  '1539024146 18826 end calculation,
  '1539024146 18826 4',
  '1539024146 19825 remove number']

I need parser this array to obtain array only with commands. Example:

['add number 1',
'update number 1 1',
'remove number']

My try:

var fs = require('fs');

var array = fs.readFileSync('log.txt').toString().split('\n');

for(var i = 0; i < array.length; i++){
//removing time
array[i] = array[i].replace(/\d{10}[ ]\d{5}/, "");
}
console.log(array);

Upvotes: 3

Views: 62

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

One approach might be to iterate your array and then remove any log entries which do not contain a keyword indicating a command. We can use a regex alternation for this:

(add|start|end|update|remove)

Here is a code sample:

var array = [ '1539024146 17827 add number 1',
  '1539024146 18826 start calculation',
  '1539024146 18826 end calculation',
  '1539024146 18826 14',
  '1539024146 18826 update number 1 1',
  '1539024146 18826 start calculation',
  '1539024146 18826 end calculation',
  '1539024146 18826 4',
  '1539024146 19825 remove number'];

var i = array.length;
while (i--) {
    if (!/(add|start|end|update|remove)/.test(array[i])) {
        array.splice(i, 1);
    } 
}

console.log(array);

Upvotes: 1

Related Questions