Asked • 05/06/19

Regex defined outside of for loop not working?

Long time user, first time asker; very new to regular expressions. I'm a designer trying to make my life in InDesign easier, so please be patient if this is an easy one :) I'm working on a script that pulls pages out of a master file into a template file. Some of these master pages have layers that are to be used when the final file is exported to PDF for print; other layers are to be used when the final file is exported to e-mailing. So, if someone checks an option to save for e-mailing, I want the print layers to hide and the e-mail layers to show. Easy enough, but I wanted to streamline the code as a function so I could specify "print" or "email" as a variable, and then the script would match that to any variable that has "print" in it. Regex territory. var openDocument = app.documents.item(0); var LayerLength = openDocument.layers.length; wordToMatch = "print"; for (i=0;i<LayerLength;i++) { myRegEx = new RegExp(wordToMatch,"i"); str = openDocument.layers.item(i).name; if (str.search(myRegEx) >= 0) { openDocument.layers.item(i).visible = true; } } So, this actually works. It does what I want it to do (Haven't put it in a function yet but I'll get there). It finds layers with "print" in them and then makes them visible. This didn't seem ideal to me, though. I thought it would make more sense to define the regex once and then use it multiple times in the for loop, as follows: wordToMatch = "print"; myRegEx = new RegExp(wordToMatch,"i"); for (i=0;i<LayerLength;i++) { str = openDocument.layers.item(i).name; if (str.search(myRegEx) >= 0) { openDocument.layers.item(i).visible = true; } } But this only does what it's supposed to do on the first layer, then it's unable to match any subsequent layers. Why is this? I feel like I'm misunderstanding something fundamental here, and I'd like to know what that is. Thanks, Brendan

1 Expert Answer

By:

Christopher M. answered • 08/04/22

Tutor
New to Wyzant

Experienced JavaScript Developer

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.