首页 > 解决方案 > 如何在 Google Apps 脚本中的每个点之后添加一个新行

问题描述

基于 Google Doc 文档,我正在创建一个 Google Apps 脚本,它将 Google Doc 文档表格中的可用文本插入到 Google Sheet 中。由于有时文本很长,谷歌表格中插入的文本看起来不太好。也使用过sheet.autoResizeColumns(3,sheet.getLastColumn()),但由于文本的长度,它看起来不太好。

所以我想在每个点之后在字符串文本中添加一个新行。我试过testText = testText.replace('.','\n')了,但这只是用新的 Line 替换了第一个点,并且还删除了这个点。我想要的是在整个字符串中的点之后有一个新行,所以不要删除点。示例:

var testText = 'This approach is very good. Thank you very much for your Attention. We will send you messages.'

想要的文字:

var wantedText = 'This approach is very good.
                  Thank you very much for your Attention.
                  We will send you messages.'

如何在 Google Apps 脚本中执行此操作?

标签: google-apps-scriptgoogle-sheetsreplacenewline

解决方案


请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals:使用反引号(重音)字符而不是双引号或单引号

function literals(){
  var wantedText = `This approach is very good.
Thank you very much for your Attention.
We will send you messages.`
  Logger.log(wantedText)
}

如果文本来自单元格,请使用:

function breakLine(){
  var testText = 'This approach is very good. Thank you very much for your Attention. We will send you messages.'
  var wantedText = testText.replace(/(\.)/gm,"\.\n");
  Logger.log(wantedText)
}

如有必要,在点后添加一个空格

var wantedText = testText.replace(/(\. )/gm,"\.\n");

推荐阅读