javascript - 使用 Google Apps 脚本 replaceText() 不适用于问号

标签 javascript google-apps-script

我有一个我编写的 Google Apps Script 脚本,它使用:

paragraph.replaceText(sentences[j], edit);

如果 sentences[j] 以问号结尾,则产生的变化等同于

edit + "?"

例如:

paragraph.replaceText("How are you?", "Hello world!");

将我的文档更改为“Hello World!?”而不是“Hello World!”

这只发生在问号上。我已经用句点、感叹号和省略号对其进行了测试。

我已经尝试了一些事情:

  • replaceText("?","stuff") 并得到了“?”的无效正则表达式。

  • replaceText(/\?/, "stuff") 和问号不变。

  • replaceText(/\?\?/, "?") 不会引发错误,它只是不会更改任何内容。

造句我做

var lines = paragraph.getText().split(/\b(\?|\!|\.\.\.|\u2026|\. \. \.|\.|\n\r|\r\n|\n|\r)/g);
var sentences = [];
for(j=0;j < lines.length;j = j+2){
  sentences.push(lines[j]+lines[j+1]); 
}

它可以很好地捕获问号。 有人知道如何解决这个问题吗?

最佳答案

搜索模式作为字符串传递,而不是 JavaScript 正则表达式对象。这就是为什么以正则表达式开头的 replaceText 调用不会改变任何内容:

replaceText(/\?/, "stuff"); //and the question marks don't change.
replaceText(/\?\?/, "?");// doesn't throw an error, it just doesn't change anything.

? 本身不是有效的正则表达式(因此出现错误)。
x? 表示零或一个 x,更喜欢一个

如果你不想让?有特殊意义,你可以转义它。这会工作...

paragraph.replaceText("How are you\?", "Hello world!");

当然,您需要在 sentences 数组中替换所有具有特殊含义的字符。

This is a list of a all the characters that need to be escaped because they have a special meaning in Google's RE2 library.

关于javascript - 使用 Google Apps 脚本 replaceText() 不适用于问号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46261450/

相关文章:

google-apps-script - 如何在谷歌电子表格中自动添加时间戳

google-apps-script - 部署 UI Web 应用程序

javascript - 如何以 Angular 动态地在 Bootstrap 模型中添加字段

Javascript::图像预览

function - 在 Google 表格的 Google 脚本中的特定表格上使用 onedit() 触发器

mysql - 带 IF 语句的 for 循环不会退出

csv - 将 Google Sheet CSV 传输到 Dropbox 的编程方式

javascript - 选中复选框时形成对象数组 angularjs

javascript - Ajax 脚本管理器命名空间

javascript - iOS Firefox XMLHttpRequest 错误响应