Google scripts docs italicize appended text

2019-09-01 04:56发布

I'm creating a report from a google spreadsheet that has a repeating pattern. I want to make the first line of each block of text italicized.

the text looks like this:

Re: Blah Blah Blah
Blah, blah blahblahblah; blah blah blah; blahblah blah.
[blah blah 10 hours at $250]

And I want everything from the Re: to the \n to be italicized. This pattern repeats throughout the document.

Here's what I currently have:

  var bodyText = body.editAsText();
  var stuff = "";
  for (i=0; i<ParNormal.length; i++){
    if (ParNormal[i].indexOf("Re: ")<0){
      bodyText.appendText(ParNormal[i]+'\n').setItalic(true);
    } else {
      bodyText.appendText(ParNormal[i]+'\n');
    }
  }

Each ParNormal array item contains a line of text and the spaces between the blocks of text are also contained inside the array (in the above example, ParNormal[3]==" ")

The code I have above doesn't work. The documentation seems to indicate that appendText returns a text element. So at the least I'd expect everything to be italicized, if not the text that I just appended. Appending paragraphs would seem to be the easiest way to do it, but it puts carriage returns at the end of each paragraph and that would mess up the presentation.

ParNormal would look like this:

[1]=="Re: Blah Blah Blah"
[2]=="Blah, blah blahblahblah; blah blah blah; blahblah blah."
[3]=="[blah blah 10 hours at $250]"
[4]==" "
[5]=="Re: Blah Blah"
[6]=="blahblah; blah."
[7]=="[blah blah blah 20]";
[8]==" "

et cetera.

1条回答
何必那么认真
2楼-- · 2019-09-01 05:11

This might be what your looking for. Used your var names where I could. Hopfully you can extrapolate what you need.

function someFunction(){
  var d = DocumentApp.getActiveDocument();
  var body = d.getBody(); 
  var parNormal = body.editAsText();
  var index = -1;
  var textFound = body.findText("Re: ");
  var text = textFound.getElement().asText();

  while(true)
 {
   index = parNormal.getText().indexOf("Re: ",index+1);
   if(index == -1)
     break;
   else {
        parNormal.setItalic(index+4, index+text.getText().length-1, true);
   }
 }
查看更多
登录 后发表回答