Home > Back-end >  How to get the first dollar value from the text retrieved from the plain body from a Gmail email bod
How to get the first dollar value from the text retrieved from the plain body from a Gmail email bod

Time:01-27

I have a Gmail Google App script. How do I retrieve the dollar values from the email plain body?

  const messageFortisBC = GmailApp.search('from:([email protected]) AND has:attachment AND newer_than:7d')[0].getMessages()[0];
  const forwardedPlainMessageFortisBC = messageFortisBC.getPlainBody();

  const messageBCHydro  = GmailApp.search('from:([email protected]) AND subject:bill AND newer_than:7d')[0].getMessages()[0];
  const forwardedPlainMessageBCHydro = messageBCHydro.getPlainBody();

Example of input values for variable forwardedPlainMessageFortisBC. This value is partial and at the beginning of the text:

Image of getPlainBody for messageFortisBC

Example of input values for variable forwardedPlainMessageBCHydro. This value is partial and somewhere half way of the text:

Your pre-authorized payment of $246.96

I have tried the match and search methods for strings. They returned -1.

CodePudding user response:

I suspect that there are many ways to answer this question.

This is via Regex.

var regex = new RegExp(/[\$](\d (?:\.\d{1,2})?)/gm)

const forwardedPlainMessageFortisBC = messageFortisBC.getPlainBody()
var valueFortis = regex.exec(forwardedPlainMessageFortisBC)
Logger.log(valueFortis[0]) 

const forwardedPlainMessageBCHydro = messageBCHydro.getPlainBody();
var valueHYDRO = regex.exec(forwardedPlainMessageFortisBC)
Logger.log(valueHYDRO[0]) 

Sample input/output

hydro

  • Related