问题描述:

I want to replace a word "allowance" with "Some text", after running the code, It will remove word allowance and apply "Some text" with same formatting as that of "allowance" but foreground color property is not getting set as that of original.I want Some text also in red color as shown in the screenshot

function retainFormatting() {

var doc = DocumentApp.getActiveDocument();

var textToHighlight = 'allowance';

var highlightStyle;

var paras = doc.getParagraphs();

var textLocation = {};

var i;

for (i=0; i<paras.length; ++i) {

textLocation = paras[i].findText(textToHighlight);

if (textLocation != null && textLocation.getStartOffset() != -1) {

highlightStyle = textLocation.getElement().getAttributes(textLocation.getStartOffset());

textLocation.getElement().deleteText(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive());

textLocation.getElement().insertText(textLocation.getStartOffset(),"Some text");

textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);

}

}

}

before setting attribute at offset

after setting attribute it turns out to be

网友答案:

getForegroundColor(offset)

Retrieves the foreground color at the specified character offset.

And

setForegroundColor(startOffset, endOffsetInclusive, color)

Sets the foreground color for the specified character range.

Here is a sample code :

Getting Color from text

highlightColor = textLocation.getElement().getForegroundColor(textLocation.getStartOffset());

Applying color to text

textLocation.getElement().setForegroundColor(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);

I hope it helps. Goodluck :)

网友答案:

Try

textLocation.getElement().editAsText().deleteText(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive());
textLocation.getElement().editAsText().insertText(textLocation.getStartOffset(),"Some text");

The .editAsText() puts you into editing the contents of the rich text leaving the existing attributes as a 'wrapper'

Alternatively, try replacing the text rather than deleting and inserting

paras[i].replaceText("allowance", "some text") // the first attribute is a regular expression as string
网友答案:

I have just tested this and it seems that setting LINK_URL alongside other attributes interferes with FOREGROUND_COLOR.

The following results in a black text color:

      var attrs = {
        "FOREGROUND_COLOR": "#ff0000", // should be red
        "LINK_URL": null
      };
      text.setAttributes(start, end, attrs);

The following results in a red text color:

      var attrs = {
        "FOREGROUND_COLOR": "#ff0000" // should be red
      };
      text.setAttributes(start, end, attrs);

In effect, if you don't need to set the link, remove the LINK_URL from the list of formatting options.

相关阅读:
Top