Replace first occurrence of text using replaceText(searchPattern, replacement)

无人久伴 提交于 2020-01-06 03:51:29

问题


I am trying to replace the first occurrence of a paragraph in Google Doc using the function replaceText(searchPattern, replacement), but I can't seem to find the right RegEx expression. If someone could help me I would really appreciate it.

body.replaceText("^"+paragraph.getText()+"$"," ");

回答1:


The body.ReplaceText() function replaces all instances of a pattern, not just the first instance ( link ).

A better option may be to loop through the paragraphs to find the first with matching text, like so:

function deleteParagraph(textToRemove) {
  var body = DocumentApp.getActiveDocument().getBody();
 // gets all paragraphs as an array
  var paragraphs = body.getParagraphs()
  for (var i = 0; i < paragraphs.length; i++){
    if (paragraphs[i].getText() === textToRemove){
      paragraphs[i].clear()
      Logger.log(textToRemove + " was removed")
      //stops it looping through any more paragraphs
      break;
    }
  }
}

If you want to practice with regular expressions then www.regexr.com is very handy.



来源:https://stackoverflow.com/questions/30105989/replace-first-occurrence-of-text-using-replacetextsearchpattern-replacement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!