Home > Back-end >  Replace brackets and everything within brackets with empty space (delete)
Replace brackets and everything within brackets with empty space (delete)

Time:12-13

I have to apologize I'm a complete newb... I'm trying to learn how to code using Google Apps Script. I would like the script to run and delete all brackets "[]" and everything within the brackets and replace with an empty space... I understand its best to do a loop but I'm just trying to get the basic function to execute.

My current code is...

function myFunction() {
  
  var body = DocumentApp.getActiveDocument().getBody();

body.replaceText("\\[1]", "");
body.replaceText("\\[2]", "");
body.replaceText("\\[3]", "");


}

But this only deletes the brackets and specified characters.. Is there a wildcard string? Thank you in advance.

CodePudding user response:

The first parameter to replaceText() is a regular expression, specifically a RE2 regex. Try this:

  body.replaceText('\\[[\\s\\S]*?\\]', '');

Note that regex special characters need to be double escaped because the regex is passed as a text string.

CodePudding user response:

Try this:

body.replaceText('\\[.*\\]','');
  • Related