Class Text

Текст

Элемент, представляющий область форматированного текста. Весь текст в Document содержится в элементах Text . Элемент Text может содержаться внутри Equation , EquationFunction , ListItem или Paragraph , но не может сам содержать какой-либо другой элемент. Дополнительную информацию о структуре документа см. в руководстве по расширению Google Docs .

var body = DocumentApp.getActiveDocument().getBody();

// Use editAsText to obtain a single text element containing
// all the characters in the document.
var text = body.editAsText();

// Insert text at the beginning of the document.
text.insertText(0, 'Inserted text.\n');

// Insert text at the end of the document.
text.appendText('\nAppended text.');

// Make the first half of the document blue.
text.setForegroundColor(0, text.getText().length / 2, '#00FFFF');

Методы

Метод Тип возврата Краткое описание
appendText(text) Text Добавляет указанный текст в конец этой текстовой области.
copy() Text Возвращает отдельную глубокую копию текущего элемента.
deleteText(startOffset, endOffsetInclusive) Text Удаляет диапазон текста.
editAsText() Text Получает Text версию текущего элемента для редактирования.
findText(searchPattern) RangeElement Ищет в содержимом элемента указанный текстовый шаблон с помощью регулярных выражений.
findText(searchPattern, from) RangeElement Ищет в содержимом элемента указанный текстовый шаблон, начиная с заданного результата поиска.
getAttributes() Object Получает атрибуты элемента.
getAttributes(offset) Object Извлекает атрибуты по указанному смещению символов.
getBackgroundColor() String Получает настройку цвета фона.
getBackgroundColor(offset) String Получает цвет фона по указанному смещению символов.
getFontFamily() String Получает настройку семейства шрифтов.
getFontFamily(offset) String Извлекает семейство шрифтов по указанному смещению символов.
getFontSize() Number Получает настройку размера шрифта.
getFontSize(offset) Number Получает размер шрифта по указанному смещению символов.
getForegroundColor() String Получает настройку цвета переднего плана.
getForegroundColor(offset) String Получает цвет переднего плана по указанному смещению символа.
getLinkUrl() String Получает URL-адрес ссылки.
getLinkUrl(offset) String Получает URL-адрес ссылки по указанному смещению символов.
getNextSibling() Element Извлекает следующий родственный элемент элемента.
getParent() ContainerElement Извлекает родительский элемент элемента.
getPreviousSibling() Element Извлекает предыдущий родственный элемент элемента.
getText() String Извлекает содержимое элемента в виде текстовой строки.
getTextAlignment() TextAlignment Получает выравнивание текста.
getTextAlignment(offset) TextAlignment Получает выравнивание текста для одного символа.
getTextAttributeIndices() Integer[] Извлекает набор текстовых индексов, которые соответствуют началу отдельных запусков форматирования текста.
getType() ElementType Получает ElementType элемента.
insertText(offset, text) Text Вставляет указанный текст по заданному смещению символов.
isAtDocumentEnd() Boolean Определяет, находится ли элемент в конце Document .
isBold() Boolean Возвращает выделенный жирным шрифтом параметр.
isBold(offset) Boolean Извлекает настройку полужирного шрифта по указанному смещению символов.
isItalic() Boolean Получает настройку курсива.
isItalic(offset) Boolean Извлекает настройку курсива по указанному смещению символов.
isStrikethrough() Boolean Получает настройку зачеркивания.
isStrikethrough(offset) Boolean Извлекает настройку зачеркивания по указанному смещению символов.
isUnderline() Boolean Получает настройку подчеркивания.
isUnderline(offset) Boolean Извлекает настройку подчеркивания по указанному смещению символов.
merge() Text Объединяет элемент с предыдущим одноуровневым элементом того же типа.
removeFromParent() Text Удаляет элемент из его родителя.
replaceText(searchPattern, replacement) Element Заменяет все вхождения данного текстового шаблона заданной строкой замены, используя регулярные выражения.
setAttributes(startOffset, endOffsetInclusive, attributes) Text Применяет указанные атрибуты к заданному диапазону символов.
setAttributes(attributes) Text Устанавливает атрибуты элемента.
setBackgroundColor(startOffset, endOffsetInclusive, color) Text Устанавливает цвет фона для указанного диапазона символов.
setBackgroundColor(color) Text Устанавливает цвет фона.
setBold(bold) Text Устанавливает жирный шрифт.
setBold(startOffset, endOffsetInclusive, bold) Text Устанавливает настройку жирного шрифта для указанного диапазона символов.
setFontFamily(startOffset, endOffsetInclusive, fontFamilyName) Text Устанавливает семейство шрифтов для указанного диапазона символов.
setFontFamily(fontFamilyName) Text Устанавливает семейство шрифтов.
setFontSize(startOffset, endOffsetInclusive, size) Text Устанавливает размер шрифта для указанного диапазона символов.
setFontSize(size) Text Устанавливает размер шрифта.
setForegroundColor(startOffset, endOffsetInclusive, color) Text Устанавливает цвет переднего плана для указанного диапазона символов.
setForegroundColor(color) Text Устанавливает цвет переднего плана.
setItalic(italic) Text Устанавливает курсив.
setItalic(startOffset, endOffsetInclusive, italic) Text Устанавливает курсив для указанного диапазона символов.
setLinkUrl(startOffset, endOffsetInclusive, url) Text Устанавливает URL-адрес ссылки для указанного диапазона символов.
setLinkUrl(url) Text Устанавливает URL-адрес ссылки.
setStrikethrough(strikethrough) Text Устанавливает настройку зачеркивания.
setStrikethrough(startOffset, endOffsetInclusive, strikethrough) Text Устанавливает настройку зачеркивания для указанного диапазона символов.
setText(text) Text Устанавливает текстовое содержимое.
setTextAlignment(startOffset, endOffsetInclusive, textAlignment) Text Устанавливает выравнивание текста для заданного диапазона символов.
setTextAlignment(textAlignment) Text Устанавливает выравнивание текста.
setUnderline(underline) Text Устанавливает настройку подчеркивания.
setUnderline(startOffset, endOffsetInclusive, underline) Text Устанавливает настройку подчеркивания для указанного диапазона символов.

Подробная документация

appendText(text)

Добавляет указанный текст в конец этой текстовой области.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Adds the text, 'Sample body text,' to the end of the document body.
const text = body.editAsText().appendText('Sample body text');

Параметры

Имя Тип Описание
text String Текст для добавления.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

copy()

Возвращает отдельную глубокую копию текущего элемента.

Любые дочерние элементы, присутствующие в элементе, также копируются. У нового элемента нет родителя.

Возвращаться

Text — Новая копия.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

deleteText(startOffset, endOffsetInclusive)

Удаляет диапазон текста.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
 const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Deletes the first 10 characters in the body.
 const text = body.editAsText().deleteText(0, 9);

Параметры

Имя Тип Описание
startOffset Integer Смещение первого символа, который нужно удалить.
endOffsetInclusive Integer Смещение символа последнего удаляемого символа.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

editAsText()

Получает Text версию текущего элемента для редактирования.

Используйте editAsText для управления содержимым элементов в виде форматированного текста. Режим editAsText игнорирует нетекстовые элементы (такие как InlineImage и HorizontalRule ).

Дочерние элементы, полностью содержащиеся в удаленном текстовом диапазоне, удаляются из элемента.

var body = DocumentApp.getActiveDocument().getBody();

// Insert two paragraphs separated by a paragraph containing an
// horizontal rule.
body.insertParagraph(0, "An editAsText sample.");
body.insertHorizontalRule(0);
body.insertParagraph(0, "An example.");

// Delete " sample.\n\n An" removing the horizontal rule in the process.
body.editAsText().deleteText(14, 25);

Возвращаться

Text — текстовая версия текущего элемента.


findText(searchPattern)

Ищет в содержимом элемента указанный текстовый шаблон с помощью регулярных выражений.

Некоторые функции регулярных выражений JavaScript, такие как группы захвата и модификаторы режима, поддерживаются не полностью.

Предоставленный шаблон регулярного выражения независимо сопоставляется с каждым текстовым блоком, содержащимся в текущем элементе.

Параметры

Имя Тип Описание
searchPattern String образец для поиска

Возвращаться

RangeElement — результат поиска, указывающий позицию искомого текста, или значение NULL, если совпадений нет.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

findText(searchPattern, from)

Ищет в содержимом элемента указанный текстовый шаблон, начиная с заданного результата поиска.

Некоторые функции регулярных выражений JavaScript, такие как группы захвата и модификаторы режима, поддерживаются не полностью.

Предоставленный шаблон регулярного выражения независимо сопоставляется с каждым текстовым блоком, содержащимся в текущем элементе.

Параметры

Имя Тип Описание
searchPattern String образец для поиска
from RangeElement результат поиска для поиска

Возвращаться

RangeElement — результат поиска, указывающий следующую позицию искомого текста, или значение NULL, если совпадений нет.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getAttributes()

Получает атрибуты элемента.

Результатом является объект, содержащий свойство для каждого допустимого атрибута элемента, где каждое имя свойства соответствует элементу в перечислении DocumentApp.Attribute .

var body = DocumentApp.getActiveDocument().getBody();

// Append a styled paragraph.
var par = body.appendParagraph('A bold, italicized paragraph.');
par.setBold(true);
par.setItalic(true);

// Retrieve the paragraph's attributes.
var atts = par.getAttributes();

// Log the paragraph attributes.
for (var att in atts) {
  Logger.log(att + ":" + atts[att]);
}

Возвращаться

Object — Атрибуты элемента.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getAttributes(offset)

Извлекает атрибуты по указанному смещению символов.

Результатом является объект, содержащий свойство для каждого допустимого текстового атрибута, где каждое имя свойства соответствует элементу в перечислении DocumentApp.Attribute .

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Declares style attributes.
const style = {}
style[DocumentApp.Attribute.BOLD] = true;
style[DocumentApp.Attribute.ITALIC] = true;
style[DocumentApp.Attribute.FONT_SIZE] = 29;

// Sets the style attributes to the document body.
const text = body.editAsText();
text.setAttributes(style);

// Gets the style attributes applied to the eleventh character in the
// body and logs them to the console.
const attributes = text.getAttributes(10);
console.log(attributes);

Параметры

Имя Тип Описание
offset Integer Смещение символов.

Возвращаться

Object — Атрибуты элемента.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getBackgroundColor()

Получает настройку цвета фона.

Возвращаться

String — цвет фона, отформатированный в нотации CSS (например '#ffffff' ), или значение NULL, если элемент содержит несколько значений для этого атрибута.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getBackgroundColor(offset)

Получает цвет фона по указанному смещению символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456');

// Gets the document body.
const body = doc.getBody();

// Sets the background color of the first 3 characters in the body.
const text = body.editAsText().setBackgroundColor(0, 2, '#FFC0CB');

// Gets the background color of the first character in the body.
const backgroundColor = text.getBackgroundColor(0);

// Logs the background color to the console.
console.log(backgroundColor);

Параметры

Имя Тип Описание
offset Integer Смещение символов.

Возвращаться

String — цвет фона, отформатированный в нотации CSS (например '#ffffff' ).

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getFontFamily()

Получает настройку семейства шрифтов. Имя может быть любым шрифтом из меню «Шрифт» в Документах или Google Fonts с учетом регистра. Методы getFontFamily() и setFontFamily(fontFamilyName) теперь используют строковые имена для шрифтов вместо перечисления FontFamily . Хотя это перечисление устарело, оно останется доступным для совместимости со старыми сценариями.

Возвращаться

String — семейство шрифтов или значение NULL, если элемент содержит несколько значений для этого атрибута.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getFontFamily(offset)

Извлекает семейство шрифтов по указанному смещению символов. Имя может быть любым шрифтом из меню «Шрифт» в Документах или Google Fonts с учетом регистра. Методы getFontFamily() и setFontFamily(fontFamilyName) теперь используют строковые имена для шрифтов вместо перечисления FontFamily . Хотя это перечисление устарело, оно останется доступным для совместимости со старыми сценариями.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the font of the first 16 characters to Impact.
const text = body.editAsText().setFontFamily(0, 15, 'Impact');

// Gets the font family of the 16th character in the document body.
const fontFamily = text.getFontFamily(15);

// Logs the font family to the console.
console.log(fontFamily);

Параметры

Имя Тип Описание
offset Integer Смещение символов.

Возвращаться

String — Семейство шрифтов.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getFontSize()

Получает настройку размера шрифта.

Возвращаться

Number — размер шрифта или значение NULL, если элемент содержит несколько значений для этого атрибута.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getFontSize(offset)

Получает размер шрифта по указанному смещению символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the font size of the first 13 characters to 15.
const text = body.editAsText().setFontSize(0, 12, 15);

// Gets the font size of the first character.
const fontSize = text.getFontSize(0);

// Logs the font size to the console.
console.log(fontSize);

Параметры

Имя Тип Описание
offset Integer Смещение символов.

Возвращаться

Number — Размер шрифта.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getForegroundColor()

Получает настройку цвета переднего плана.

Возвращаться

String — цвет переднего плана, отформатированный в нотации CSS (например '#ffffff' ), или значение NULL, если элемент содержит несколько значений для этого атрибута.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getForegroundColor(offset)

Получает цвет переднего плана по указанному смещению символа.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the foreground color of the first 3 characters in the document body.
const text = body.editAsText().setForegroundColor(0, 2, '#0000FF');

// Gets the foreground color of the first character in the document body.
const foregroundColor = text.getForegroundColor(0);

// Logs the foreground color to the console.
console.log(foregroundcolor);

Параметры

Имя Тип Описание
offset Integer Смещение символов.

Возвращаться

String — цвет переднего плана, отформатированный в нотации CSS (например '#ffffff' ).

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getLinkUrl()

Получает URL-адрес ссылки.

Возвращаться

String — URL-адрес ссылки или значение NULL, если элемент содержит несколько значений для этого атрибута.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getLinkUrl(offset)

Получает URL-адрес ссылки по указанному смещению символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Applies a link to the first 10 characters in the body.
const text = body.editAsText().setLinkUrl(0, 9, 'https://www.example.com/');

// Gets the URL of the link from the first character.
const link = text.getLinkUrl(0);

// Logs the link URL to the console.
console.log(link);

Параметры

Имя Тип Описание
offset Integer Смещение символов.

Возвращаться

String — URL-адрес ссылки.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getNextSibling()

Извлекает следующий родственный элемент элемента.

Следующий брат имеет того же родителя и следует за текущим элементом.

Возвращаться

Element — следующий родственный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getParent()

Извлекает родительский элемент элемента.

Родительский элемент содержит текущий элемент.

Возвращаться

ContainerElement — Родительский элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getPreviousSibling()

Извлекает предыдущий родственный элемент элемента.

Предыдущий одноуровневый элемент имеет того же родителя и предшествует текущему элементу.

Возвращаться

Element — предыдущий родственный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getText()

Извлекает содержимое элемента в виде текстовой строки.

Возвращаться

String — содержимое элемента в виде текстовой строки.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getTextAlignment()

Получает выравнивание текста. Доступные типы выравнивания: DocumentApp.TextAlignment.NORMAL , DocumentApp.TextAlignment.SUBSCRIPT и DocumentApp.TextAlignment.SUPERSCRIPT .

Возвращаться

TextAlignment — тип выравнивания текста или null , если текст содержит несколько типов выравнивания текста или если выравнивание текста никогда не устанавливалось.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getTextAlignment(offset)

Получает выравнивание текста для одного символа. Доступные типы выравнивания: DocumentApp.TextAlignment.NORMAL , DocumentApp.TextAlignment.SUBSCRIPT и DocumentApp.TextAlignment.SUPERSCRIPT .

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the text alignment of the document body to NORMAL.
const text = body.editAsText().setTextAlignment(DocumentApp.TextAlignment.NORMAL);

// Gets the text alignment of the ninth character.
const alignment = text.getTextAlignment(8);

// Logs the text alignment to the console.
console.log(alignment.toString());

Параметры

Имя Тип Описание
offset Integer Смещение персонажа.

Возвращаться

TextAlignment — Тип выравнивания текста или null , если выравнивание текста никогда не задавалось.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getTextAttributeIndices()

Извлекает набор текстовых индексов, которые соответствуют началу отдельных запусков форматирования текста.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Gets the text indices at which text formatting changes.
const indices = body.editAsText().getTextAttributeIndices();

// Logs the indices to the console.
console.log(indices.toString());

Возвращаться

Integer[] — Набор текстовых индексов, при которых изменяется форматирование текста.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

getType()

Получает ElementType элемента.

Используйте getType() , чтобы определить точный тип данного элемента.

var body = DocumentApp.getActiveDocument().getBody();

// Obtain the first element in the document body.

var firstChild = body.getChild(0);

// Use getType() to determine the element's type.
if (firstChild.getType() == DocumentApp.ElementType.PARAGRAPH) {
  Logger.log('The first element is a paragraph.');
} else {
  Logger.log('The first element is not a paragraph.');
}

Возвращаться

ElementType — Тип элемента.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

insertText(offset, text)

Вставляет указанный текст по заданному смещению символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Inserts the text, 'Sample inserted text', at the start of the body content.
const text = body.editAsText().insertText(0, 'Sample inserted text');

Параметры

Имя Тип Описание
offset Integer Смещение символа, по которому вставляется текст.
text String Текст для вставки.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

isAtDocumentEnd()

Определяет, находится ли элемент в конце Document .

Возвращаться

Boolean — находится ли элемент в конце документа.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

isBold()

Возвращает выделенный жирным шрифтом параметр.

Возвращаться

Boolean — выделен ли текст полужирным шрифтом или имеет значение null, если элемент содержит несколько значений для этого атрибута.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

isBold(offset)

Извлекает настройку полужирного шрифта по указанному смещению символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Bolds the first 4 characters in the document body.
const text = body.editAsText().setBold(0, 3, true);

// Gets whether or not the text is bold.
const bold = text.editAsText().isBold(0);

// Logs the text's bold setting to the console
console.log(bold);

Параметры

Имя Тип Описание
offset Integer Смещение символов.

Возвращаться

Boolean — жирный шрифт.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

isItalic()

Получает настройку курсива.

Возвращаться

Boolean — выделен ли текст курсивом или имеет значение null, если элемент содержит несколько значений для этого атрибута.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

isItalic(offset)

Извлекает настройку курсива по указанному смещению символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the first 13 characters of the document body to italic.
const text = body.editAsText().setItalic(0, 12, true);

// Gets whether the fifth character in the document body is set to
// italic and logs it to the console.
const italic = text.isItalic(4);
console.log(italic);

Параметры

Имя Тип Описание
offset Integer Смещение символов.

Возвращаться

Boolean — курсив.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

isStrikethrough()

Получает настройку зачеркивания.

Возвращаться

Boolean — зачеркнут ли текст или имеет значение null, если элемент содержит несколько значений для этого атрибута.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

isStrikethrough(offset)

Извлекает настройку зачеркивания по указанному смещению символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the first 17 characters of the document body to strikethrough.
const text = body.editAsText().setStrikethrough(0, 16, true);

// Gets whether the first character in the document body is set to
// strikethrough and logs it to the console.
const strikethrough = text.isStrikethrough(0);
console.log(strikethrough);

Параметры

Имя Тип Описание
offset Integer Смещение символов.

Возвращаться

Boolean — настройка зачеркивания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

isUnderline()

Получает настройку подчеркивания.

Возвращаться

Boolean — подчеркнут ли текст или имеет значение null, если элемент содержит несколько значений для этого атрибута.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

isUnderline(offset)

Извлекает настройку подчеркивания по указанному смещению символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the first 13 characters of the document body to underline.
const text = body.editAsText().setUnderline(0, 12, false);

// Gets whether the first character in the document body is set to
// underline and logs it to the console
const underline = text.editAsText().isUnderline(0);
console.log(underline);

Параметры

Имя Тип Описание
offset Integer Смещение символов.

Возвращаться

Boolean — настройка подчеркивания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

merge()

Объединяет элемент с предыдущим одноуровневым элементом того же типа.

Объединять можно только элементы одного и того же ElementType . Любые дочерние элементы, содержащиеся в текущем элементе, перемещаются в предыдущий родственный элемент.

Текущий элемент удаляется из документа.

var body = DocumentApp.getActiveDocument().getBody();
// Example 1: Merge paragraphs
// Append two paragraphs to the document.
var par1 = body.appendParagraph('Paragraph 1.');
var par2 = body.appendParagraph('Paragraph 2.');
// Merge the newly added paragraphs into a single paragraph.
par2.merge();

// Example 2: Merge table cells
// Create a two-dimensional array containing the table's cell contents.
var cells = [
['Row 1, Cell 1', 'Row 1, Cell 2'],
['Row 2, Cell 1', 'Row 2, Cell 2']
];
// Build a table from the array.
var table = body.appendTable(cells);
// Get the first row in the table.
 var row = table.getRow(0);
// Get the two cells in this row.
var cell1 = row.getCell(0);
var cell2 = row.getCell(1);
// Merge the current cell into its preceding sibling element.
var merged = cell2.merge();

Возвращаться

Text — объединенный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

removeFromParent()

Удаляет элемент из его родителя.

var body = DocumentApp.getActiveDocument().getBody();

// Remove all images in the document body.
var imgs = body.getImages();
for (var i = 0; i < imgs.length; i++) {
  imgs[i].removeFromParent();
}

Возвращаться

Text — удаленный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

replaceText(searchPattern, replacement)

Заменяет все вхождения данного текстового шаблона заданной строкой замены, используя регулярные выражения.

Шаблон поиска передается в виде строки, а не объекта регулярного выражения JavaScript. По этой причине вам необходимо избегать любых обратных косых черт в шаблоне.

В этом методе используется библиотека регулярных выражений Google RE2 , которая ограничивает поддерживаемый синтаксис .

Предоставленный шаблон регулярного выражения независимо сопоставляется с каждым текстовым блоком, содержащимся в текущем элементе.

var body = DocumentApp.getActiveDocument().getBody();

// Clear the text surrounding "Apps Script", with or without text.
body.replaceText("^.*Apps ?Script.*$", "Apps Script");

Параметры

Имя Тип Описание
searchPattern String шаблон регулярного выражения для поиска
replacement String текст, который будет использоваться в качестве замены

Возвращаться

Element — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setAttributes(startOffset, endOffsetInclusive, attributes)

Применяет указанные атрибуты к заданному диапазону символов.

Указанный параметр атрибутов должен быть объектом, где каждое имя свойства является элементом перечисления DocumentApp.Attribute , а каждое значение свойства — новым применяемым значением.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body and edits as text.
const body = doc.getBody().editAsText();

// Declares style attributes for font size and font family.
const style = {}
style[DocumentApp.Attribute.FONT_SIZE] = 20 ;
style[DocumentApp.Attribute.FONT_FAMILY] = 'Impact';

// Sets the style attributes to the first 9 characters in the document body.
const text = body.setAttributes(0, 8, style);

Параметры

Имя Тип Описание
startOffset Integer Смещение начала текстового диапазона.
endOffsetInclusive Integer Смещение конца текстового диапазона.
attributes Object Атрибуты элемента.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setAttributes(attributes)

Устанавливает атрибуты элемента.

Указанный параметр атрибутов должен быть объектом, где каждое имя свойства является элементом перечисления DocumentApp.Attribute , а каждое значение свойства — новым применяемым значением.

var body = DocumentApp.getActiveDocument().getBody();

// Define a custom paragraph style.
var style = {};
style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] =
    DocumentApp.HorizontalAlignment.RIGHT;
style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
style[DocumentApp.Attribute.FONT_SIZE] = 18;
style[DocumentApp.Attribute.BOLD] = true;

// Append a plain paragraph.
var par = body.appendParagraph('A paragraph with custom style.');

// Apply the custom style.
par.setAttributes(style);

Параметры

Имя Тип Описание
attributes Object Атрибуты элемента.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setBackgroundColor(startOffset, endOffsetInclusive, color)

Устанавливает цвет фона для указанного диапазона символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the background color of the first 3 characters in the
// document body to hex color #0000FF.
const text = body.editAsText().setBackgroundColor(0, 2, '#0000FF');

Параметры

Имя Тип Описание
startOffset Integer Смещение начала текстового диапазона.
endOffsetInclusive Integer Смещение конца текстового диапазона.
color String Цвет фона, отформатированный в нотации CSS (например '#ffffff' ).

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setBackgroundColor(color)

Устанавливает цвет фона.

Параметры

Имя Тип Описание
color String цвет фона, отформатированный в нотации CSS (например '#ffffff' )

Возвращаться

Text — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setBold(bold)

Устанавливает жирный шрифт.

Параметры

Имя Тип Описание
bold Boolean смелая настройка

Возвращаться

Text — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setBold(startOffset, endOffsetInclusive, bold)

Устанавливает настройку жирного шрифта для указанного диапазона символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the first 11 characters in the document body to bold.
const text = body.editAsText().setBold(0, 10, true);

Параметры

Имя Тип Описание
startOffset Integer Смещение начала текстового диапазона.
endOffsetInclusive Integer Смещение конца текстового диапазона.
bold Boolean Смелая постановка.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setFontFamily(startOffset, endOffsetInclusive, fontFamilyName)

Устанавливает семейство шрифтов для указанного диапазона символов. Имя может быть любым шрифтом из меню «Шрифт» в Документах или Google Fonts с учетом регистра. Нераспознанные имена шрифтов будут отображаться как Arial. Методы getFontFamily(offset) и setFontFamily(fontFamilyName) теперь используют строковые имена для шрифтов вместо перечисления FontFamily . Хотя это перечисление устарело, оно останется доступным для совместимости со старыми сценариями.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets body of the document.
const body = doc.getBody();

// Sets the font of the first 4 characters in the document body to Roboto.
const text = body.editAsText().setFontFamily(0, 3, 'Roboto');

Параметры

Имя Тип Описание
startOffset Integer Смещение начала текстового диапазона.
endOffsetInclusive Integer Смещение конца текстового диапазона.
fontFamilyName String Название семейства шрифтов из меню «Шрифт» в Документах или Google Fonts.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setFontFamily(fontFamilyName)

Устанавливает семейство шрифтов. Имя может быть любым шрифтом из меню «Шрифт» в Документах или Google Fonts с учетом регистра. Нераспознанные имена шрифтов будут отображаться как Arial. Методы getFontFamily() и setFontFamily(fontFamilyName) теперь используют строковые имена для шрифтов вместо перечисления FontFamily . Хотя это перечисление устарело, оно останется доступным для совместимости со старыми сценариями.

Параметры

Имя Тип Описание
fontFamilyName String название семейства шрифтов из меню «Шрифт» в Документах или Google Fonts.

Возвращаться

Text — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setFontSize(startOffset, endOffsetInclusive, size)

Устанавливает размер шрифта для указанного диапазона символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the size of the first 11 characters in the document body to 12.
const text = body.editAsText().setFontSize(0, 10, 12);

Параметры

Имя Тип Описание
startOffset Integer Смещение начала текстового диапазона.
endOffsetInclusive Integer Смещение конца текстового диапазона.
size Number Размер шрифта.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setFontSize(size)

Устанавливает размер шрифта.

Параметры

Имя Тип Описание
size Number размер шрифта

Возвращаться

Text — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setForegroundColor(startOffset, endOffsetInclusive, color)

Устанавливает цвет переднего плана для указанного диапазона символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the foreground color of the first 2 characters in the
// document body to hex color #FF0000.
const text = body.editAsText().setForegroundColor(0, 1, '#FF0000');

// Gets the foreground color for the second character in the document body.
const foregroundColor = text.getForegroundColor(1);

//  Logs the foreground color to the console.
console.log(foregroundColor);

Параметры

Имя Тип Описание
startOffset Integer Смещение начала текстового диапазона.
endOffsetInclusive Integer Смещение конца текстового диапазона.
color String Цвет переднего плана, отформатированный в нотации CSS (например '#ffffff' ).

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setForegroundColor(color)

Устанавливает цвет переднего плана.

Параметры

Имя Тип Описание
color String цвет переднего плана, отформатированный в нотации CSS (например '#ffffff' )

Возвращаться

Text — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setItalic(italic)

Устанавливает курсив.

Параметры

Имя Тип Описание
italic Boolean курсив

Возвращаться

Text — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setItalic(startOffset, endOffsetInclusive, italic)

Устанавливает курсив для указанного диапазона символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the first 11 characters in the document body to italic.
const text = body.editAsText().setItalic(0, 10, true);

Параметры

Имя Тип Описание
startOffset Integer Смещение начала текстового диапазона.
endOffsetInclusive Integer Смещение конца текстового диапазона.
italic Boolean Курсив.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setLinkUrl(startOffset, endOffsetInclusive, url)

Устанавливает URL-адрес ссылки для указанного диапазона символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Applies a link to the first 11 characters in the body.
const text = body.editAsText().setLinkUrl(0, 10, 'https://example.com');

Параметры

Имя Тип Описание
startOffset Integer Смещение начала текстового диапазона.
endOffsetInclusive Integer Смещение конца текстового диапазона.
url String URL-адрес ссылки.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setLinkUrl(url)

Устанавливает URL-адрес ссылки.

Параметры

Имя Тип Описание
url String URL-адрес ссылки

Возвращаться

Text — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setStrikethrough(strikethrough)

Устанавливает настройку зачеркивания.

Параметры

Имя Тип Описание
strikethrough Boolean настройка зачеркивания

Возвращаться

Text — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setStrikethrough(startOffset, endOffsetInclusive, strikethrough)

Устанавливает настройку зачеркивания для указанного диапазона символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the first 11 characters in the document body to strikethrough.
const text = body.editAsText().setStrikethrough(0, 10, true);

Параметры

Имя Тип Описание
startOffset Integer Смещение начала текстового диапазона.
endOffsetInclusive Integer Смещение конца текстового диапазона.
strikethrough Boolean Настройка зачеркивания.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setText(text)

Устанавливает текстовое содержимое.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Replaces the contents of the body with the text, 'New body text.'
const text = body.editAsText().setText('New body text.');

Параметры

Имя Тип Описание
text String Новое текстовое содержание.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setTextAlignment(startOffset, endOffsetInclusive, textAlignment)

Устанавливает выравнивание текста для заданного диапазона символов. Доступные типы выравнивания: DocumentApp.TextAlignment.NORMAL , DocumentApp.TextAlignment.SUBSCRIPT и DocumentApp.TextAlignment.SUPERSCRIPT .

// Make the first character in the first paragraph be superscript.
var text = DocumentApp.getActiveDocument().getBody().getParagraphs()[0].editAsText();
text.setTextAlignment(0, 0, DocumentApp.TextAlignment.SUPERSCRIPT);

Параметры

Имя Тип Описание
startOffset Integer Начальное смещение диапазона символов.
endOffsetInclusive Integer Конечное смещение диапазона символов (включительно).
textAlignment TextAlignment Тип выравнивания текста, который необходимо применить.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setTextAlignment(textAlignment)

Устанавливает выравнивание текста. Доступные типы выравнивания: DocumentApp.TextAlignment.NORMAL , DocumentApp.TextAlignment.SUBSCRIPT и DocumentApp.TextAlignment.SUPERSCRIPT .

// Make the entire first paragraph be superscript.
var text = DocumentApp.getActiveDocument().getBody().getParagraphs()[0].editAsText();
text.setTextAlignment(DocumentApp.TextAlignment.SUPERSCRIPT);

Параметры

Имя Тип Описание
textAlignment TextAlignment тип выравнивания текста, который нужно применить

Возвращаться

Text — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setUnderline(underline)

Устанавливает настройку подчеркивания.

Параметры

Имя Тип Описание
underline Boolean настройка подчеркивания

Возвращаться

Text — текущий элемент

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents

setUnderline(startOffset, endOffsetInclusive, underline)

Устанавливает настройку подчеркивания для указанного диапазона символов.

// Opens the Docs file by its URL. If you created your script from within a
// Google Docs file, you can use DocumentApp.getActiveDocument() instead.
// TODO(developer): Replace the URL with your own.
const doc = DocumentApp.openByUrl('https://docs.google.com/document/d/abc123456/edit');

// Gets the document body.
const body = doc.getBody();

// Sets the first 11 characters in the document body to underline.
const text = body.editAsText().setUnderline(0, 10, true);

Параметры

Имя Тип Описание
startOffset Integer Смещение начала текстового диапазона.
endOffsetInclusive Integer Смещение конца текстового диапазона.
underline Boolean Настройка подчеркивания.

Возвращаться

Text — текущий элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/documents.currentonly
  • https://www.googleapis.com/auth/documents