InDesign: how to remove everything between square brackets

I have a script to find all textframes in a document, and do a regular expression to remove (if contains) all text inside square brackets.

For example the text frame might contain:

“Lorem ipsum dolor sit amet, consectetur adipiscing elit [test] Lorem ipsum dolor sit amet, consectetur adipiscing elit [test2]”

i have written the following script to find all textframes content then replace them using regex, but only does 1 per text frame and doesnt apply to all

If i run the below script, it gets rid of [test] but not [test2]

var myFrames = app.activeDocument.textFrames;

for (var i = 0; i<myFrames.length; i++) {
   var myFrame = myFrames[i];
   var string = myFrame.contents;
   var string2 = string.replace(/ *\[[^\]]*]/, '');
   myFrame.contents = string2;
}

Answer

You don’t need to script this, just

  • hit Ctrl+F and switch to the ‘GREP’ tab
  • type \[[^]]*\] in the ‘Find what’ field
  • or type the same thing with an \s? added in front to also remove any preceding whitespace, otherwise you’ll be left with double spaces. so that’s \s?\[[^]]*\]
  • make sure the ‘Change to’ field is empty
  • click ‘Change All’

enter image description here

Attribution
Source : Link , Question Author : lanes123 , Answer Author : Lucian

Leave a Comment