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!
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);
I believe your goal is as follows.
You want to insert a value of "blabla" in the text of body.
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?
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");
In your script, htmlBody is used. If you want to use the result value as HTML body, please modify join("\n") to join("<br>").
As an additional information, if your value of body is more than 9 paragraphs and you want to include all paragraphs, how about modifying var res = [...p.slice(6, 9), "blabla", ...p.slice(0, 6)].join("\n"); and var 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");From your following reply,
Input:
<br>p1<br>p2<br>p3<br>p4Output at goal:<br>p1<br>p2<br>blabla<br>p3<br>p4Output I actually get:p1 p2 blabla p3 p4I miss the<br>in my output, but I WANT them.
In this case, how about the following sample script?
var body = "<br>p1<br>p2<br>p3<br>p4";
var p = body.split("<br>");
p.splice(3, 0, "blabla");
var res = p.join("<br>");
console.log(res) // <br>p1<br>p2<br>blabla<br>p3<br>p4
<br>p1<br>p2<br>p3<br>p4, you can see the sample output value of <br>p1<br>p2<br>blabla<br>p3<br>p4 you expect.