0

I have the following text taken from a email body, I want to save each block into a object, then add into a array. but I am struggle to correctly define the for loop, in another word how to seprate the blocks

Name: Andy
Computer: ABC
IP: 192.168.0.1
Added By: Maria
Timestamp: 2018-03-15 08:45:08 +0000 UTC

Name: Richard
Computer: CDE
IP: 192.168.0.2
Timestamp: 2018-03-15 08:45:08 +0000 UTC

..........more blocks................

In Javascript (Jquery can not be supported)

//I first define a array  
var msgs= [];

//then define a object
var msg= {
    Name:"",
    Computer:"",
    IP:50,
    TimeStamp: new Date()
};

var reg = (.....);
var result;

//wholeMsgBody is the whole text sample I have provided
while((result = reg.exec(wholeMsgBody)) !== null) {
  //assume the block = Name:.... until TimeStamp.....
  var userName = block.match(Name:.*); //Andy
  var computer = block.match(Computer:.*); //ABC
  var ip = block.match(Computer:.*) //192.168.0.1
  Var timeStamp = new Date(block.match(Timestamp:.*)) //2018/03/15

  msgs.push({"Name":userName, "Computer":computer, "ip":ip, "timeStamp":timeStamp})
}

I am basiclly Struggle to define the reg expression. any help would be much appriciated.

2
  • What is your struggle? Please show us what you tried and what problem you were facing specifically. Commented Apr 3, 2018 at 19:16
  • You don't really need a regex (it might actually be more complicated to use one since this format may not necessarily be regular) it would be easier to just looking at the first word of a line, you know name means new object and then you know the order of the data values afterwards, you could just create a while loop that goes line by line and parses the data (using regex or whatever) Commented Apr 3, 2018 at 19:19

1 Answer 1

2

You should be able to separate the blocks by calling split() on the string and passing the appropriate separator. After this you can split it into lines, and then key/value pairs.

Of course, if your data is not consistent you will need to adjust, but something like this might get you started:

var str = `Name: Andy
Computer: ABC
IP: 192.168.0.1
Added By: Maria
Timestamp: 2018-03-15 08:45:08 +0000 UTC

Name: Richard
Computer: CDE
IP: 192.168.0.2
Timestamp: 2018-03-15 08:45:08 +0000 UTC
`

var blocks = str.split('\n\n')
var objects = blocks.map(b => {
    let lines = b.split('\n')
    return lines.reduce((obj, line) => {
        if (!line) return obj
        let [key, value] = line.split(/:(.+)/)
        obj[key] = value.trim()
        return obj
    }, {})

})
console.log(objects)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.