Class Text

Текст

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

// Gets the body contents of the active tab.
var body = DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();

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

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

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

// Make the first half of the tab 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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

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

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

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

Авторизация

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

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

editAsText()

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

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

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

var body = DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().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, такие как группы захвата и модификаторы режима, поддерживаются не полностью.

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

Параметры

ИмяТипОписание
searchPatternStringшаблон для поиска

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

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

Авторизация

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

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

findText(searchPattern, from)

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

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

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

Параметры

ИмяТипОписание
searchPatternStringшаблон для поиска
fromRangeElementрезультат поиска для поиска

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

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

Авторизация

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

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

getAttributes()

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

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

var doc = DocumentApp.getActiveDocument();
var documentTab = doc.getActiveTab().asDocumentTab();
var body = documentTab.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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().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 tab's 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);

Параметры

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

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

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/DOCUMENT_ID');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().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);

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().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 tab body.
const fontFamily = text.getFontFamily(15);

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().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);

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

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

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().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);

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

// Sets the text alignment of the tab's 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());

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().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 doc = DocumentApp.getActiveDocument();
var documentTab = doc.getActiveTab().asDocumentTab();
var body = documentTab.getBody();

// Obtain the first element in the active tab's 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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

ИмяТипОписание
offsetIntegerСмещение символа, по которому вставляется текст.
textStringТекст для вставки.

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

// Bolds the first 4 characters in the tab 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);

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

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

Параметры

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

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

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

Авторизация

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

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

merge()

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

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

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

var doc = DocumentApp.getActiveDocument();
var documentTab = doc.getActiveTab().asDocumentTab();
var body = documentTab.getBody();

// Example 1: Merge paragraphs
// Append two paragraphs to the document's active tab.
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 doc = DocumentApp.getActiveDocument();
var documentTab = doc.getActiveTab().asDocumentTab()
var body = documentTab.getBody();

// Remove all images in the active tab's 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().getActiveTab().asDocumentTab().getBody();

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

// 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 tab's body.
const text = body.setAttributes(0, 8, style);

Параметры

ИмяТипОписание
startOffsetIntegerСмещение начала текстового диапазона.
endOffsetInclusiveIntegerСмещение конца текстового диапазона.
attributesObjectАтрибуты элемента.

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

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

Авторизация

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

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

setAttributes(attributes)

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

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

var doc = DocumentApp.getActiveDocument();
var documentTab = doc.getActiveTab().asDocumentTab();
var body = documentTab.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);

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

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

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

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

Авторизация

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

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

setBackgroundColor(color)

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

Параметры

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

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

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

Авторизация

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

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

setBold(bold)

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

ИмяТипОписание
startOffsetIntegerСмещение начала текстового диапазона.
endOffsetInclusiveIntegerСмещение конца текстового диапазона.
boldBooleanСмелая постановка.

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

ИмяТипОписание
startOffsetIntegerСмещение начала текстового диапазона.
endOffsetInclusiveIntegerСмещение конца текстового диапазона.
fontFamilyNameStringНазвание семейства шрифтов из меню «Шрифт» в Документах или 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 . Хотя это перечисление устарело, оно останется доступным для совместимости со старыми скриптами.

Параметры

ИмяТипОписание
fontFamilyNameStringназвание семейства шрифтов из меню «Шрифт» в Документах или 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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

ИмяТипОписание
startOffsetIntegerСмещение начала текстового диапазона.
endOffsetInclusiveIntegerСмещение конца текстового диапазона.
sizeNumberРазмер шрифта.

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

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

Авторизация

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

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

setFontSize(size)

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

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

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

Параметры

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

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

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

Авторизация

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

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

setForegroundColor(color)

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

Параметры

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

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

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

Авторизация

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

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

setItalic(italic)

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

ИмяТипОписание
startOffsetIntegerСмещение начала текстового диапазона.
endOffsetInclusiveIntegerСмещение конца текстового диапазона.
italicBooleanКурсив.

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

ИмяТипОписание
startOffsetIntegerСмещение начала текстового диапазона.
endOffsetInclusiveIntegerСмещение конца текстового диапазона.
urlStringURL-адрес ссылки.

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

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

Авторизация

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

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

setLinkUrl(url)

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

Параметры

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

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

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

Авторизация

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

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

setStrikethrough(strikethrough)

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

ИмяТипОписание
startOffsetIntegerСмещение начала текстового диапазона.
endOffsetInclusiveIntegerСмещение конца текстового диапазона.
strikethroughBooleanНастройка зачеркивания.

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

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

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

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 of the active tab be superscript.
var documentTab = DocumentApp.getActiveDocument().getActiveTab().asDocumentTab();
var text = documentTab.getBody().getParagraphs()[0].editAsText();
text.setTextAlignment(0, 0, DocumentApp.TextAlignment.SUPERSCRIPT);

Параметры

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

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

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 in the active tab be superscript.
var documentTab = DocumentApp.getActiveDocument().getActiveTab().asDocumentTab();
var text = documentTab.getBody().getParagraphs()[0].editAsText();
text.setTextAlignment(DocumentApp.TextAlignment.SUPERSCRIPT);

Параметры

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

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

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

Авторизация

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

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

setUnderline(underline)

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

Параметры

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

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

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/DOCUMENT_ID/edit');

// Gets the body contents of the tab by its ID.
// TODO(developer): Replace the ID with your own.
const body = doc.getTab(TAB_ID).asDocumentTab().getBody();

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

Параметры

ИмяТипОписание
startOffsetIntegerСмещение начала текстового диапазона.
endOffsetInclusiveIntegerСмещение конца текстового диапазона.
underlineBooleanНастройка подчеркивания.

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

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

Авторизация

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

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