Class Text

Текст

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

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' ), или нуль, если элемент содержит несколько значений для этого атрибута.

Авторизация

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

  • 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' ), или нуль, если элемент содержит несколько значений для этого атрибута.

Авторизация

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

  • 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 — будет ли текст выделен полужирным или нулевым, если элемент содержит несколько значений для этого атрибута.

Авторизация

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

  • 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 — будет ли текст выделен курсивом или нулевым, если элемент содержит несколько значений для этого атрибута.

Авторизация

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

  • 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