【问题标题】:Google Apps Script replaceText() not working with apostrophe " ' "Google Apps 脚本 replaceText() 不适用于撇号“'”
【发布时间】:2017-10-03 18:18:29
【问题描述】:

在我的代码中,当我尝试将“don't”替换为“do not”时,它不起作用,但当我使用常规单词时,它会起作用。我试图用“不要”来逃避。 有没有特殊的方法来转义谷歌应用脚​​本中的字符?

//Sidebar.html
function doWordReplace(value) { 
   if(value.checked) {
      google.script.run.withSuccessHandler(print).wordReplace("don't");
   }
   else {}
}

//Replace.gs
function wordReplace(findMe) {
    var text = DocumentApp.getActiveDocument().getBody().editAsText();
    text.replaceText(findMe, "do not");
  return "replacement successful";

}

【问题讨论】:

    标签: javascript regex string google-apps-script


    【解决方案1】:

    使用replace() 而不是replaceText()

    function wordReplace(findMe) {
        var text = DocumentApp.getActiveDocument().getBody().getText();
    
        // Use Unicode for right single quotation mark
        // \u2018-left single, \u2019-right single, \u0027-apostrophe
        text.replace(/don\u2019t/gi, "do not");
        DocumentApp.getActiveDocument().getBody().setText(text);
    
      return "replacement successful";
    }
    

    【讨论】:

    • 替换不是 Google Apps 脚本中的功能吗?
    • 这是 javascript,可用于 google 应用程序脚本项目。刚刚在一个新的工作表脚本和独立脚本项目中再次对其进行了测试。
    • 好的,这意味着我需要首先将文本对象作为字符串获取正确吗?
    • 看起来应该是var text = DocumentApp.getActiveDocument().getBody().getText(),然后是.setText(text)。我没有使用DocumentApp() 方法,并认为这是您正在检索的字符串。
    • 它仍然不适合我。使用replace(),它仍然不会让我用撇号替换单词,但常规单词确实有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多