I am trying to forward an email and add a paragraph after the 6th paragraph in the original message which looks like this:
p1
p2
p3
p4
p5
p6
p7
p8
p9
I have this script (only part of it is shown below):
var body = messages[j].getPlainBody();
var firstpart = body.split("\n")[7,8,9]);
var secondpart = body.split("\n")[1,2,3,4,5,6]);
GmailApp.sendEmail(recipient,subject, '', {htmlBody: "blabla" body});
Instead of this, I would like to have something like that:
var body = messages[j].getPlainBody();
var firstpart = body.split("\n")[7,8,9]);
var secondpart = body.split("\n")[1,2,3,4,5,6]);
GmailApp.sendEmail(recipient,subject, '', {htmlBody: firstpart "blabla" secondpart});
This does not work, as the split returns only one paragraph. Is there a way to include all first 6 paragraphs and all last paragraphs in variables?
Many thanks in advance!
CodePudding user response:
You could do a regex replacement here:
var input = "p1\np2\np3\np4\np5\np6\np7\np8\np9";
var output = input.replace(/^((?:[\s\S]*?\n){6})/, "$1blabla\n");
console.log(output);
CodePudding user response:
I believe your goal is as follows.
You want to insert a value of
"blabla"
in the text ofbody
.From your script of
Instead of this, I would like to have something like that:
, you want to achieve the following result.p7 p8 p9 blabla p1 p2 p3 p4 p5 p6
In your situation, how about the following modification?
Modified script:
var body = messages[j].getPlainBody();
var p = body.split("\n");
var res = [...p.slice(6, 9), "blabla", ...p.slice(0, 6)].join("\n");
GmailApp.sendEmail(recipient, subject, '', { htmlBody: res });
When this script is run, the above result is obtained.
If you want to retrieve the following result,
p1 p2 p3 p4 p5 p6 blabla p7 p8 p9
Please modify
var res = [...p.slice(6, 9), "blabla", ...p.slice(0, 6)].join("\n");
as follows.var res = [...p.slice(0, 6), "blabla", ...p.slice(6, 9)].join("\n");
Note:
In your script,
htmlBody
is used. If you want to use the result value as HTML body, please modifyjoin("\n")
tojoin("<br>")
.As an additional information, if your value of
body
is more than 9 paragraphs and you want to include all paragraphs, how about modifyingvar res = [...p.slice(6, 9), "blabla", ...p.slice(0, 6)].join("\n");
andvar res = [...p.slice(0, 6), "blabla", ...p.slice(6, 9)].join("\n");
as follows?var res = [...p.slice(6), "blabla", ...p.slice(0, 6)].join("\n");
var res = [...p.slice(0, 6), "blabla", ...p.slice(6)].join("\n");