Bayrem Ben Alaya
Bayrem Ben Alaya

Reputation: 297

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

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()+"$"," ");

Upvotes: 1

Views: 842

Answers (1)

CaptainNemo
CaptainNemo

Reputation: 256

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.

Upvotes: 2

Related Questions