Apps Scriptリファレンス: Apps Script Reference |障害・課題追跡: IssueTracker |Google Workspace: Status Dashboard - Summary

2019年9月5日木曜日

Googleドキュメント内のテキストを置換したい replaceText


DocumentApp.getActiveDocument().getBody()
でBodyを取得して

.replaceText(searchPattern, replacement)
で置換できるようです。



ドキュメント内に hello world という文字列があって


コード.gsの
body.replaceText("hello", "Hello")
でhello を Hello に置換できます。



コード.gs
function myFunction() {
  var doc = DocumentApp.getActiveDocument()
  var body = doc.getBody();
  body.replaceText("hello", "Hello");
}
意訳
この機能がやること
ドキュメントを取得して
Bodyを取得して
hello を Hello に置換する



補足

  • 正規表現も使えるようです
  • 一致するすべてのsearchPatternがreplacementで置換されます
    • すべて置換


ドキュメント内に
hello world
hello world2
という文字列があるとき

コード.gsの
body.replaceText("hello", "Hello");
body.replaceText("hello.*", "Hi");
に書き換えて実行すると以下のようになります。


参考

replaceText(searchPattern, replacement)
https://developers.google.com/apps-script/reference/document/text#replaceText(String,String)

Class Body
https://developers.google.com/apps-script/reference/document/body
The Body may contain ListItem, Paragraph, Table, and TableOfContents elements. For more information on document structure, see the guide to extending Google Docs.

Latest post

Google Formsで動画を追加したい

今回はGoogleフォームに「動画を追加」してみます フォームの編集画面 YouTube全体を検索またはURLを貼り付けます 今回は特定のURLを貼り付けてみます 検索結果で対象の動画を選択して右下の「挿入」ボタンをクリックします フォームに動画が追加されます タイトルや質問を入...