Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js string parser

Tags:

node.js

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);

1 Answers

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);
like image 103
Tim Biegeleisen Avatar answered Feb 24 '26 17:02

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!