javascriptparsingname-value

Parse Email Body with Multiple Lines


How would I go about parsing a email body with multiple lines in javascript?

Example

Employee:

123456789

Name:

John Doe

This is what I'm using right now.

var emailObj = {};

var body_text = inputs.email.replace(/<\/?[^>]+(>|$)/g, ""); 
var regEx = /^(.+):(.+)$/;


for (var i = 0; i < valPairs.length; i++) {
  matches = valPairs[i].match(regEx);
  emailObj[matches[1].toString().trim()] = matches[2].toString().trim(); 
}

outputs.email_var = emailObj;

Thank you.


Solution

  • You can first filter out the empty lines by splitting by a newline and using Array.filter.

    The object can be constructed by using Array.reduce and checking whether the index is even or not. If it is, set the property name and value to the according items in the array.

    const str = `Employee:
    
    123456789
    
    Name:
    
    John Doe`;
    
    const lines = str.split("\n").filter(e => e != "");
    
    const obj = lines.reduce((a, b, i) => {
      if (i % 2 != 0) {
        a[lines[i - 1]] = lines[i]
      }
      return a;
    }, {})
    
    console.log(obj)